2016-11-24 138 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