NodeJS + Mongoose:人口不起作用

时间:2013-06-26 18:55:03

标签: node.js mongoose populate

我想向Blog对象添加几个Categories个对象,之后可以访问Blog的第一个类别。

var ObjectId = mongoose.Schema.Types.ObjectId;

var categorySchema = mongoose.Schema({
    title: String,
    blogs: [{ type: ObjectId, ref: 'Blog' }]
})

var blogSchema = mongoose.Schema({
    title: String,
    description: String,
    category: [{ type: ObjectId, ref: 'Category' }],
    created: {type: Number, default: new Date().getTime()}
})

var Category = mongoose.model('Category', categorySchema)
var Blog = mongoose.model('Blog', blogSchema)

exports.addBlog = function (object, callback) {
    Blog({
        title: object.title,
        description: object.description,
        category: object.category //array of sting ObjectID's - ['',''] – from multiselect box
    }).save(function (err, _) {
            Blog
                .find({title: _.title})
                .populate('category')
                .exec(function (err, __) {
                    if (err) return handleError(err);
                    console.log('Category is ', __.category[0].title);
                })
            callback(err, _);
        });
}

结果我得到了:

TypeError: Cannot read property '0' of undefined

似乎Mongoose在最后一个回调(__)中找不到对象,但我检查过 - _.title是有效的。如何填充它?感谢。

1 个答案:

答案 0 :(得分:1)

问题是Blog.find()返回一个数组,我应该使用__[0].category[0].title或找到findOne()