4

I am using MongooseDeepPopulate package for the project. I have SchemaA, SchemaB, SchemaC, SchemaD. My SchemaD, SchemaC are connected to SchemaB and SchemaB is connected to SchemaA.

I have done like this.

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

song is connection further with category and poetId. I am successfull with limiting fields from category and poetId. But I wish to limit fields from intermediate model song as well. My find query is like

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

Where I have mistaken.

Sankalp
  • 1,300
  • 5
  • 28
  • 52

1 Answers1

1

If you want to limit the fields for the AlbumSong, you can just use the feature provided by mongoose itself, like this:

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

Here is a simple application to demonstrate the idea. Schema looks like this:

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

The deepPopulate settings above limit fields for related author, comments and comments.author. To get posts and limit fields for the post itself, I use this:

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

The data looks like this:

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

So for the post itself we only have title (body is not selected). For populated records the selected fields are limited as well.

Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54