1.0.2 • Published 2 years ago

mongoose-hydrate-populated-data v1.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

mongoose-hydrate-populated-data

npm i --save mongoose-hydrate-populated-data

State: model has relation with collection1 and collection2, like:

import { model, Schema } from 'mongoose'

const mySchema: Schema<MyDocument> = new Schema({
  fieldName1: {
    type: Schema.Types.ObjectId,
    ref: collection1,
    required: false,
    index: true
  },
  fieldName2: {
    type: Schema.Types.ObjectId,
    ref: collection2,
    required: true,
    index: true
  },
})
  • Use populatingLookupPreserveNullQuery for collection1,

    • because model may have null in collection1 reference due to required: false.
  • Use populatingLookupQuery for collection2,

    • because model cannot have null in collection2 reference due to required: true.
import { FilterQuery } from 'mongoose'
import { populatingLookupPreserveNullQuery, populatingLookupQuery, hydratePopulated } from 'mongoose-hydrate-populated-data'

const records = await model.aggregate([
  {
    $match: FilterQuery<any>
  },
  ...populatingLookupPreserveNullQuery(collection1, fieldName1),
  ...populatingLookupQuery(collection2, fieldName2),
])

records.map((record) => hydratePopulated(model, record, [fieldName1, fieldName2]))

https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/#document-operand-with-options