Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS+;猫鼬:种群不起作用_Node.js_Mongoose_Populate - Fatal编程技术网

Node.js NodeJS+;猫鼬:种群不起作用

Node.js NodeJS+;猫鼬:种群不起作用,node.js,mongoose,populate,Node.js,Mongoose,Populate,我想向博客对象添加几个类别对象,然后访问博客的第一个类别 var ObjectId = mongoose.Schema.Types.ObjectId; var categorySchema = mongoose.Schema({ title: String, blogs: [{ type: ObjectId, ref: 'Blog' }] }) var blogSchema = mongoose.Schema({ title: String, descript

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

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

问题是
Blog.find()
返回一个数组,我应该使用
\uuu[0].category[0]。title
或findOne()查找第一眼:似乎没有定义
\uuuuu.category
,因为错误消息说0,这是唯一一个0的地方。@gustavohenke我已经解决了:问题是Blog.find()返回一个数组,我应该使用_[0].category[0]。title或findOne()查找