Home > Software design >  Difference between Model.find({key: "value"}) and Model.find().where("key").equa
Difference between Model.find({key: "value"}) and Model.find().where("key").equa

Time:07-25

Consider the following code

const mongoose = require('mongoose');

main().catch((err) => console.log(err));

const Model = mongoose.model('collection', new mongoose.Schema({ ... }));

async function main() {
  const connection = await mongoose.connect(`mongodb://localhost:27017/DB`); 
  // Method 1 
  const doc1 = await Model.find({ key: 'value' });
  console.log(doc1); 
  // Method 2 
  const doc2 = await Model.find().where('key').equals('value');
  mongoose.connection.close();
  console.log(doc1);
}

Model.find() returns a <Query> Object which is chainable.

Q1• What is a <Query> Object. Is it a promise?

Q2• What is the difference between Method1 and Method2 ?

CodePudding user response:

Q1. The <Query> Object, is not a promise. You should note, Model.find() does not return a promise, it is not asynchronous and your wouldn't use await. <Query> is an instance of the Query class. It contains information about your query and has a number of functions available to it such as where() and equals().

A full list of functions is available here: https://mongoosejs.com/docs/api.html#Query

It is the returned <Query> Object which allows the chaining.

Q2. The main difference between these two methods is semantic. They both perform the same function. Method 1 allows you to pass the query parameters as an object. Method 2 performs the same action through function chaining.

  • Related