'Mongoose: setting default populate options

I have a schema in mongoose that references another schema, eg:

OrderSchema = new Schema({
  createdBy: {
     ref: 'User',
     type: ObjectId
  }
})

In my user schema, I'm using a soft-delete plugin to keep references. For normal user find queries, the plugin adds a where {deleted: {$ne: true}} to the query using a pre find hook.

When I try to find all orders with createdBy populated, the deleted query is also applied so that any (soft) deleted users are not populated. I can bybass the soft delete query by supplying a "includeDeleted" parameter in population options, this works well for specific queries.

I would like to be able to specify this option in the schema definition so that im not relying on every query to include the options, eg:

// doesnt work, options are not supplied to populate query
OrderSchema = new Schema({
  createdBy: {
     ref: 'User',
     type: ObjectId,
     options: {
       includeDeleted: true
     }
  }
})

Virtual populates does work this way:

// WORKS
OrderSchema.virtual('_createdBy', {
   ref: 'User',
   ...,
   options: {
      includeDeleted: true
   }
})

Maybe theres another options to supply default populate options in the schema definition? I havent been able to find anything in the documentation.

Another solution would be to manually lookup the population options in the soft-delete plugin, but that requires me to know if a query is a "population query" in the pre find hook.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source