2016-11-24 68 views
0

我了深刻的填充面临的问题,蒙戈,Node.js的深填充

var commentSchema = mongoose.Schema({ 
     name: String }); 

var userSchema = mongoose.Schema({ 
    userId: { type: String, default: '' }, 
    comments: [subSchema] 
}); 

var socialSchema = mongoose.Schema({ 
    userId: {type: mongoose.Schema.Types.ObjectId, ref: "user"}, 
    countryCode: { type: String, default: '' }, 
    socialId: {type: mongoose.Schema.Types.ObjectId, ref: "user"}, 
    dateAdded: { type: Date, default: Date.now } 
}); 

目的是填充“社会”的文件,并获得具有匹配id的评论。解决方案是将socialId的“ref”设置为“user.comments”,而不仅仅是用户。这样它总是返回null。

Social.find().populate('socialId').exec(function(err, feed) { 
    if (err) { 
     console.log(err); 
     throw err; 
    }else{ 
     res.json({data: feed, message:"Getting feed"}); 
    } 

    }) 

回答

0

据我所知,您可能需要再次填充它们我不认为只有一个查询中可能存在深度人口。

Social.find().populate('socialId').exec(function(err, feed) { 
    if (err) { 
    console.log(err); 
    throw err; 
    }else { 
    Comments.populate(feed, {path: 'socialId.user.comments'}, function (err, populatedFeeds) { 
     if (err) { 
     console.log(err); 
     throw err; 
     } else { 
     res.json({data: feed, message: "Getting feed"}); 
     } 
    }) 
    } 
}) 
0

有这个mongoose-deep-populate

var deepPopulate = require('mongoose-deep-populate')(mongoose); 
var Schema = new mongoose.Schema({ 
    ... 
}); 
Schema.plugin(deepPopulate); 

// while populating: 

Schema.find(...).deepPopulate({ 
    paths: [], // list of paths goes here 
    { 
     populate: { 
      'first.path': 'things to select' // space seperated list of fields to select 
     } 
    } 
}); 

猫鼬插件,你可以阅读更多关于这个here