【问题标题】:NodeJS + Mongoose: population doesnt workNodeJS + Mongoose:人口不起作用
【发布时间】:2013-06-27 05:00:30
【问题描述】:

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

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 是有效的。如何填充它?谢谢。

【问题讨论】:

  • 先看一下:好像__.category没有定义,因为错误信息说0,你只有0的地方。
  • @gustavohenke 我已经解决了:问题是 Blog.find() 返回一个数组,我应该使用 __[0].category[0].title 或 findOne()

标签: node.js mongoose populate


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 2016-08-25
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2021-05-26
    • 2017-08-23
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多