mongoose-plugin-deep-populate
DeepPopulate plugin helps you do some auto population without thinking about depth, inspired from mongoose-autopopulate.
Installation
Just run
npm install mongoose-plugin-deep-populate
or
yarn add mongoose-plugin-deep-populate
And just call it from a model created JavaScript file
const mongoose = ; const schema = ...; schema;
Or install it for all schemas
const mongoose = ; mongoose;
Usage
Let's create a School model
const SchoolSchema = name: type: String ; const School = mongoose;
And Student model
const StudentSchema = firstName: type: String lastName: type: String school: type: MongooseSchemaTypesObjectId ref: 'school' ; const Student = mongoose;
And ExamMark model
const ExamMarkSchema = student: type: MongooseSchemaTypesObjectId ref: 'student' mark: type: Number ; const ExamMark = mongoose;
And the only think we have to do to use the deep population plugin is add the deepPopulate option field
const ExamMarkSchema = ... deepPopulate: student: school: true ;
Or you want to populate only one deep level, you can also do
const ExamMarkSchema = ... deepPopulate: 'student' ;
And just call
const examMark = await ExamMark;
And with doing that every time a query runs on ExamMark model, student and school of student fields automatically populated as nested. Now, deepPopulation only works on the queries on ExamMark model, since we add options to the only ExamMark model. Any query runs on Student model does not populate school field since we have not add the deepPopulation field to the student model.
To skip the deep population step, just use skipPopulation
function
const examMark = await ExamMark;
Default value of the skipPopulation
function parameters is true
, so you can also do
const examMark = await ExamMark;