Mongoose Deep Populate限制中间模型

时间:2016-01-14 10:02:04

标签: mongoose mongoose-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'}
    }
});

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

我错了。

1 个答案:

答案 0 :(得分:1)

如果您想限制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设置限制了相关authorcommentscomments.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"
            }
        }
    ]
}]

因此,对于帖子本身,我们只有title(未选择body)。 对于填充的记录,所选字段也是有限的。