Mongoose Deep Populate限制中间模型

我正在为项目使用 MongooseDeepPopulate包.我有SchemaA,SchemaB,SchemaC,SchemaD.我的SchemaD,SchemaC连接到SchemaB,SchemaB连接到SchemaA.

我这样做了.

var deepPopulate = require('mongoose-deep-populate')(mongoose);
AlbumSong.plugin(deepPopulate, {
    populate: {
        'song.category': {select: 'name status'},
        'song.poetId': {select: 'name status'}
    }
});

歌曲与类别和poetId进一步联系.我成功地限制了类别和poetId中的字段.但我希望限制中级模特歌曲中的字段.我的查询查询就像

AlbumSong.find(condition)
    .deepPopulate('song.category song.poetId')
//  .deepPopulate('song.category song.poetId' , '_id category poetId name nameHindi invalid status') // I tried this as well to limit records from song model as well.
    .exec(function(err, playlist) {
        callback(err, playlist);
    });

在哪里我弄错了.

最佳答案 如果要限制AlbumSong的字段,可以使用 mongoose itself提供的功能,如下所示:

AlbumSong.find(condition)
   .select('_id category poetId name nameHindi invalid status')
   .deepPopulate(...)

Here is一个简单的应用程序来演示这个想法.
架构看起来像这样:

var userSchema = new Schema({
  name:  String,
  email: String
});

var CommentSchema = new Schema({
  author  : {type: Schema.Types.ObjectId, ref: 'User'},
  title: String,
  body: String
})

var PostSchema = new Schema({
  title:  String,
  author: { type: Schema.Types.ObjectId, ref: 'User' },
  comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],
  body:   String
});

PostSchema.plugin(deepPopulate, {
  populate: {
    'author': { select: 'name' },
    'comments': { select: 'title author' },
    'comments.author': { select: 'name' },
  }
});

上面的deepPopulate设置限制了相关作者,评论和comments.author的字段.
要获得帖子本身的帖子和限制字段,我使用这个:

Post.find().select('title author comments').deepPopulate('author comments.author').exec(function(err, data) {
    // process the data
});

数据如下所示:

[{
    "_id": "56b74c9c60b11e201fc8563f",
    "author": {
        "_id": "56b74c9b60b11e201fc8563d",
        "name": "Tester"
    },
    "title": "test",
    "comments": [
        {
            "_id": "56b74c9c60b11e201fc85640",
            "title": "comment1",
            "author": {
                "_id": "56b74c9b60b11e201fc8563e",
                "name": "Poster"
            }
        }
    ]
}]

所以对于帖子本身我们只有标题(未选择正文).
对于填充的记录,所选字段也是有限的.

点赞