参考和填充问题

时间:2013-04-23 12:54:43

标签: node.js mongodb express mongoose

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

我一直在尝试引用和填充mongoose和expressjs,但它根本不起作用。我跟着这些:  1. Mongoose examples  2. Mongoose populate

我创建了三个文件:

1)models / 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)models / 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)controllers / 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为null。当我评论populate()时,它是一个字符串(?),如下所示: { 标题:'我的头衔', creditsFor:'5174a9ec993af25b01000003' }

无法弄清楚什么是错的。我试图将两个模型都放在一个文件中,但仍然没有。

0 个答案:

没有答案