创建子文档后如何填充猫鼬?

2023-12-08

我正在向 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 是我的猫鼬 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)
        });
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建子文档后如何填充猫鼬? 的相关文章

随机推荐