当前位置: 动力学知识库 > 问答 > 编程问答 >

Nested populate with Mongoose

问题描述:

So I'm trying to populate already populated documents:

postModel

.findOne({

_id: postId

}).select()

.populate('author')

.populate('sharedBy')

.populate('replies')

.exec(function(err, post) {

if (err) return err;

However, the replies array will hold a bunch of Posts which have author and sharedBy keys that I also need to populate. This is my strategy:

 .populate('author')

.populate('sharedBy')

.populate('replies')

.exec(function(err, post) {

if (err) return err;

post.deepPopulate(function(err, post){

And deepPopulate:

PostSchema.method('deepPopulate', function(cb) {

var post = this;

async.map(this.replies, function(reply, done) {

mongoose.model('Post', PostSchema).findOne({

_id: reply._id

}).select().populate('author').populate('sharedBy').exec(done);

}, function(err, replies) {

post.replies = replies;

cb(err, post);

});

});

It finds the replies fine but I can't seem to put them back into the original post that was passed in! Any ideas?

网友答案:

The post is a Mongoose Document, which means that you can't overwrite properties like you have there. The quick solution is to call .toObject on the post, and then overwrite replies.

var postObj = post.toObject()
postObj.replies = replies;
cb(err, postObj);

toObject turns the Mongoose document into a regular object so you can overwrite its properties. The negative here is that, from then on, you can't use Mongoose methods on the post.

I can't help thinking there's a better way to do this.

分享给朋友:
您可能感兴趣的文章:
随机阅读: