node.js - 创建后如何在 mongoose 中填充子文档?

我正在向 item.comments 列表添加评论。在将其输出到响应中之前,我需要获取 comment.created_by 用户数据。我该怎么做?

    Item.findById(req.param('itemid'), function(err, item){
        var comment = item.comments.create({
            body: req.body.body
            , created_by: logged_in_user
        });

        item.comments.push(comment);

        item.save(function(err, item){
            res.json({
                status: 'success',
                message: "You have commented on this item",

//how do i populate comment.created_by here???

                comment: item.comments.id(comment._id)
            });
        }); //end item.save
    }); //end item.find

我需要在我的 res.json 输出中填充 comment.created_by 字段:

                comment: item.comments.id(comment._id)

comment.created_by 是我的 Mongoose CommentSchema 中的用户引用。它目前只给我一个用户 ID,我需要用所有用户数据填充它,除了密码和盐字段。

这是人们询问的架构:

var CommentSchema = new Schema({
    body          : { type: String, required: true }
  , created_by    : { type: Schema.ObjectId, ref: 'User', index: true }
  , created_at    : { type: Date }
  , updated_at    : { type: Date }
});

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true }
  , created_by  : { type: Schema.ObjectId, ref: 'User', index: true }
  , comments  : [CommentSchema]
});

最佳答案

为了填充引用的子文档,您需要显式定义 ID 引用的文档集合(如 created_by: { type: Schema.Types.ObjectId, ref: 'User' } )。

鉴于此引用已定义并且您的架构也已明确定义,您现在可以像往常一样调用 populate(例如 populate('comments.created_by') )

概念证明代码:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

最后请注意,populate 仅适用于查询,因此您需要先将项目传递到查询中,然后调用它:

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

https://stackoverflow.com/questions/13026486/

相关文章:

python - 在 Meteor 运行时,如何从另一个客户端访问 Meteor 的 MongoDB

shell - 如何从 Mongo ObjectID 中提取创建日期

mongodb - 如何使用 docker-compose 为 mongo 数据库播种?

mongodb - Mongoose:深人口(填充人口密集的领域)

mongodb - 如何从 find 方法返回 Mongoose 结果?

mongodb - meteor :如何备份我的 mongo 数据库

mongodb - 在 mongodb 中使用 findOne 获取具有最大 id 的元素

mongodb - 大型项目的 NodeJS vs Play 框架

mongodb - 仅返回嵌套数组中匹配的子文档元素

mongodb - 查询 MongoDB 的 IDE?