mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Question: Can I ignore populate in some cases? #81

Closed klaveren closed 3 years ago

klaveren commented 3 years ago

I'm have setuped in Schema with { autopopulate: true }, but, some times, I don't need all informations, some times I just want return the specific field, but all populate fields are always returns too. Have some way to prevent populate fields in specifc cenarios, like as in query options or other way, becouse the autopopulate don't respect the select params, in my case, maybe this is a my mistake. Thanks and advance.

vkarpov15 commented 3 years ago

You can disable autopopulate from Mongoose query options, for example:

    var bandSchema = new Schema({
      name: String,
      lead: { type: ObjectId, ref: 'people', autopopulate: true }
    });
    bandSchema.plugin(autopopulate);

    var Band = mongoose.model('Band', bandSchema, 'bands');
    // `{ autopopulate: false }` means skip autopopulate for this query
    Band.findOne({ name: "Guns N' Roses" }, {}, { autopopulate: false }, function(error, doc) {
      assert.ok(doc.lead instanceof mongoose.Types.ObjectId);
      assert.ok(!doc.populated('lead'));
    });
klaveren commented 3 years ago

You can disable autopopulate from Mongoose query options, for example:

    var bandSchema = new Schema({
      name: String,
      lead: { type: ObjectId, ref: 'people', autopopulate: true }
    });
    bandSchema.plugin(autopopulate);

    var Band = mongoose.model('Band', bandSchema, 'bands');
    // `{ autopopulate: false }` means skip autopopulate for this query
    Band.findOne({ name: "Guns N' Roses" }, {}, { autopopulate: false }, function(error, doc) {
      assert.ok(doc.lead instanceof mongoose.Types.ObjectId);
      assert.ok(!doc.populated('lead'));
    });

Very Many Thanks!! There is!