Mongoose深度填充:限制中间模型

4
我正在使用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 与分类和诗人ID进一步关联。我已经成功地从 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个回答

1
如果你想限制AlbumSong的字段,你可以使用mongoose本身提供的功能,像这样:
AlbumSong.find(condition)
   .select('_id category poetId name nameHindi invalid status')
   .deepPopulate(...)

这里有一个简单的应用程序来演示这个想法。架构看起来像这样:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接