【问题标题】:Mongoose Deep Populate limiting intermediate modelMongoose Deep Populate 限制中间模型
【发布时间】:2016-04-19 14:26:52
【问题描述】:

我正在为该项目使用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 与类别和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);
    });

我哪里弄错了。

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案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"
                }
            }
        ]
    }]
    

    所以对于帖子本身,我们只有titlebody 未被选中)。 对于填充的记录,所选字段也受到限制。

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 2018-06-30
      • 2018-03-29
      • 2013-06-24
      • 2014-12-01
      • 2012-07-06
      • 2018-09-10
      • 1970-01-01
      • 2018-02-06
      相关资源
      最近更新 更多