2016-11-24 3 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 } 
}); 

Цель заключается в заселить «социальный» документ и получить комментарии с согласующим идентификатором. Решение было бы установить «ref» для socialId для «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

Смежные вопросы