Search code examples
node.jsmongodbmongoose

Does the Mongoose hydrate method request a new query to the database?


I have a question about Mongoose. Does the Model.hydrate(rawDoc) method request a new query to the database? I am using aggregate method to build my query and I need to use virtuals getter, because aggregate will be returned an plain object javascript so I cannot use any features instance from mongoose document object (e.g: virtuals, statics, methods, helpers, ...). What I am doing is converting a plain javascript object returned from this aggregate to mongoose document object by using hydrate() method, but I am wondering if this way does 2 queries to database or one query only?

const rawDocs = await Model.aggregate([...]);
const newDocs = rawDocs.map(doc => Model.hydrate(doc));

console.log(newDocs); // virtual fields are defined.

Solution

  • Mongoose .hydrate() is just a way to create a Mongoose Document from a raw JS object. Docs here.

    Creating the document you can access to methods, virtuals, validations as you want... but it's not a object retrieved from the DB.

    By the way, by definition, .hydrate() is the opposite from .lean() which also doesn't need an extra call and is similar to do new Model() but this last can trigger any DB query (from hooks for example).

    So you should not have any extra DB call using .hydrate().