创建后,如何填写一个子文档? [英] How to populate a sub-document in mongoose after creating it?

查看:111
本文介绍了创建后,如何填写一个子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对item.comments列表添加评论。我需要在用户数据中输入comment.created_,然后才能在响应中输出。我应该怎么做?

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

项目。 comment.push(comment);

item.save(function(err,item){
res.json({
status:'success',
message :你已经评论过这个项目,

//如何填充comment.created_by这里???

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

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

  comment:item.comments.id(comment._id)
/ pre>

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}
,comment:[CommentSchema]
});


解决方案

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



如果定义了这个引用,并且你的模式也被很好地定义了,你可以像往常一样调用填充(例如填充('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]
});

//连接到DB和实例化模型
var db = mongoose.connect('在这里输入你的数据库');
var User = db.model('User',UserSchema);
var Comment = db.model('Comment',CommentSchema);
var Item = db.model('Item',ItemSchema);

//查找并填充
Item.find({})。populate('comments.created_by')。exec(function(err,items){
console.log (item [0] .comments [0] .created_by.name);
});

最后注意到填充仅用于查询所以您需要首先将您的项目传递到查询中,然后调用它:

  item.save(function(err,item) {
Item.findOne(item).populate('comments.created_by')。exec(function(err,item){
res.json({
status:'success',
消息:你已经评论过这个项目,
comment:item.comments.id(comment._id)
});
});
}) ;


I am adding a comment to an item.comments list. I need to get the comment.created_by user data before I output it in the response. How should I do this?

    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

I need to populate the comment.created_by field here in my res.json output:

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

comment.created_by is a user reference in my mongoose CommentSchema. It currently is only giving me a user id, I need it populated with all the user data, except for password and salt fields.

Here is the schema as people have asked:

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]
});

解决方案

In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: 'User' }).

Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate as usual (e.g. populate('comments.created_by'))

Proof of concept code:

// 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);
});

Finally note that populate works only for queries so you need to first pass your item into a query and then call it:

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)
        });
    });
});

这篇关于创建后,如何填写一个子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆