0

[已解决 - 模型中的愚蠢错误]

我一直在尝试在 mongoose 和 expressjs 中引用和填充,但它根本不起作用。我遵循了这些:1. Mongoose 示例 2. Mongoose 填充

我创建了三个文件:

1) 模型/profile.js

var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var profileSchema = new Schema({
    name: String
});
module.exports = mongoose.model('Profile', profileSchema);

2) 模型/work.js

var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

var workSchema = new Schema({
    title: String,
    creditsFor: [{type: Schema.Types.ObjectId, ref: 'profile'}],
});
module.exports = mongoose.model('Work', workSchema);

3) 控制器/work.js

var Work = require('../models/work.js'), fs = require('fs'), mongoose = require('mongoose');
......
exports.create = function(req, res) {
    credits = [];
    credits.push(mongoose.Types.ObjectId('5174a9ec993af25b01000003')); // I already created a 'Profile' and copy-pasted the _id

    var work = {
    title: req.body.title,
            creditsFor: credits
    }   

    var workObj = new Work(work);

    workObj.save(function(err, data) {
    if(err) {
        throw err;
    } else {
        req.flash('info', 'Work item saved.');
        res.redirect('/work/' + data._id);
    }
    });
}
.......
exports.show = function(req, res) {
var work = req.params.work;
Work.findOne({_id: work})
    .populate('creditsFor')
    .exec(function(err, data) {
    if(err) {
        throw err;
    } else {
        console.log(data);
        res.render('site/work/show', {work: data, message: req.flash('info')});
    }
});
}

使用 populate() 时,返回的 creditsFor 为空。当我评论 populate() 时,它是一个字符串 (?),像这样:{ title: 'My Title', creditsFor: '5174a9ec993af25b01000003' }

无法弄清楚出了什么问题。我试图将两个模型放在一个文件中,但仍然没有。

4

0 回答 0