Mongoose models provide several static helper functions for CRUD operations. Each of these functions returns a mongoose Query object.
For example :
let query = Model.find();
This returns a <Query> Object which is chainable.
async function() => {
let newQuery = query.where("key").equals("value");
let result = await newQuery;
}
Q1• What exactly is a Query Object returned from Model.find()?
Q2• How does chaining work?
Are <Query> objects like promise since I am using asynchronous functions?
Kindly link any kind of docs that might clear my issue ? I am relatively new to this so if my question makes no sense please correct me :-(
For questions like these, it is best to consult the TypeScript definitions for the module. query.d.ts in particular holds the answers.
Q1• What exactly is a Query Object returned from Model.find()?
find's signature looks as follows:
find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
callback?: Callback<ResultDoc[]> | undefined
): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
So the return type is QueryWithHelpers with some generics, which resolves to Query with some generics. Now to look at it's definition it is quite long. It is a regular object with the following implementations:
exec(), find(), findOne, etc. These are your chaining methods (Q2).[Symbol.asyncIterator](): AsyncIterableIterator<DocType>; which lets you use things like for (let .. of ..) on itthen: Promise<ResultType>['then'];. This lets you do find(...).then(...), which is the same thing the await keyword does, which makes it work as well.