node.js - NodeJS + Mongoose : population doesnt work

标签 node.js mongoose populate

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

最佳答案

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

关于node.js - NodeJS + Mongoose : population doesnt work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17328238/

相关文章:

node.js - Node js - 发送基本电子邮件时的发送网格问题

javascript - Mongoose 更新嵌套值

node.js - 将一个新对象插入 Mongoose 的子文档数组字段中

ios - JSON Swift 填充 TableView 错误

sql - 在事务中删除然后创建外键约束是否安全?

javascript - 在 Node JS 中使用 fs-extra 更新 xml 文件

node.js - 如何在当前更新的 mongodb 网站上获取标准 URI 连接字符串(不带 srv)?

javascript - meteor .js : lib folder not loaded first

node.js - 如何在 Node.js Express mongoose 后端的 URL 查询字符串中使用 $or 运算符

c++ - 填充数组