Mongoose Deep Populate 限制中间模型

Mongoose Deep Populate limiting intermediate model

我正在为项目使用 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'}
    }
});

song是跟category和poetId的进一步联系。我成功地限制了 categorypoetId 的字段。但我也希望限制来自中间模型 song 的字段。我的查找查询类似于

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' },
  }
});

相关 authorcommentscomments.authordeepPopulate 设置超出限制字段。 要获取 posts 并限制 post 本身的字段,我使用这个:

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"
            }
        }
    ]
}]

所以对于 post 本身我们只有 title(未选择 body)。 对于填充的记录,所选字段也受到限制。