Open In App

Mongoose Query API

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is a tool that allows you to define and work with documents in your MongoDB collections. One of the most important aspects of Mongoose is its Query API, which provides a set of methods for building and executing queries in your MongoDB database. In this article, we will look at some of the common Query API methods available in Mongoose and how they can be used in your application.

Overview Of Mongoose Query API

Mongoose offers a number of static methods on its models that can be used to perform CRUD (create, read, update, delete) operations on the documents in a collection. These methods return a Query object, which can be used to specify additional constraints or to execute the query.

  • Model.deleteMany(): Deletes multiple documents from the database that match the specified criteria.
  • Model.deleteOne(): Deletes a single document from the database that matches the specified criteria.
  • Model.find(): Retrieves one or more documents from the database that match the specified criteria.
  • Model.findById(): Retrieves a single document by its unique _id field.
  • Model.findByIdAndDelete(): Finds a single document by its _id field and deletes it from the database.
  • Model.findByIdAndRemove(): Finds a single document by its _id field and removes it from the database.
  • Model.findByIdAndUpdate(): Finds a single document by its _id field and updates it in the database.
  • Model.findOne(): Retrieves a single document that matches the specified criteria.
  • Model.findOneAndDelete(): Finds a single document that matches the specified criteria and deletes it from the database.
  • Model.findOneAndRemove(): Finds a single document that matches the specified criteria and removes it from the database.
  • Model.findOneAndReplace(): Finds a single document that matches the specified criteria and replaces it in the database with a new document.
  • Model.findOneAndUpdate(): Finds a single document that matches the specified criteria and updates it in the database.
  • Model.replaceOne(): Replaces a single document in the database that matches the specified criteria with a new document.
  • Model.updateMany(): Updates multiple documents in the database that match the specified criteria.
  • Model.updateOne(): Updates a single document in the database that matches the specified criteria.

Prerequisites:

  • MongoDB must be installed.
  • NodeJs must be installed. 

Connecting to a MongoDB database in our application: Before we move forward with the tutorial let us first connect MongoDB to our application and create a schema. We can then add an element to the document using the create method.

const mongoose = require("mongoose"); // npm i mongoose

mongoose.connect("mongodb://127.0.0.1:27017/gfg");

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number,
});

const User = mongoose.model("geeksforgeeks", UserSchema);

User.create(
  { name: "Rhythm Shandlya",
    age: 20,
    email: "armaanbgp@gmail.com" },
  function (err, user) {
    if (err) console.error(err);
    else console.log(user);
  }
);

 

How To Execute Mongoose Query API?

Due to its flexible nature, we can execute Query APIs in a number of ways:

1. Using A Callback Function: In this method, a callback function is passed to the query function. This callback is executed when the query fetching is complete.

Syntax:

Model.findOne(querryObject, callbackFunction);

Example:

User.findOne({ name: "Rhythm Shandlya" }, function (err, user) {
    if (err) return handleError(err);
    else console.log(user);
});

Output:

 

2. Using .then() and .catch(): 

Syntax:

Model.findById(userId).then(user){}.catch(error){}

Example:

User.findById('63b1332c8a41f608100eeffd')
    .then(function (user) {
        console.log(user);
    })
    .catch(function (err) {
        console.log(user);
    });

Output:

 

3. Using async await syntax:

Syntax:

const user = await User.findOneAndUpdate(querryObject,valueToBeUpdated,options);

Example:

const findUser = async function () {
    try {
        const user = await User.findOneAndUpdate(
            { name: "Rhythm Shandlya" },
            { age: 24 },
            { new: true }
        );
        console.log(user);
    } catch (e) {
        console.log(e);
    }

};

findUser();

Output:

 

Mongoose Query Are Different From Promises:

Mongoose queries are not promises. However, they do have a .then() function that can be used to handle the results of a query as a promise.

Here is an example of using a Mongoose query with the .then() function:

User.findOne({ name: 'Rhythm Shandlya' }).then((doc) => {
    console.log(doc);
});

The .then() function is called when the query completes, and it receives the result of the query as an argument. If the query was successful, the result will be the document that was found. If the query failed, the result will be null.

Mongoose queries are different from native JavaScript promises in a few ways:

  • Mongoose queries are not immediately executed when they are created. Instead, you need to call a method like .exec() or .then() to execute the query.
  • Mongoose queries have a number of additional methods, like .sort() and .limit(), that can be chained onto the query to specify additional constraints.
  • Mongoose queries are designed to work with MongoDB, whereas native JavaScript promises are more general purpose.

Sort Select And Limit Operations On Query Object:

The sort() function allows you to specify the order in which results should be returned by a query. You can specify the sort order using a comma-separated list of fields, with a 1 indicating ascending order and a -1 indicating descending order. For example:

Model.find({}).sort({ field1: 1, field2: -1 });

The limit() function allows you to specify the maximum number of results that should be returned by a query. For example:

Model.find({}).limit(10);

The select() function allows you to specify which fields should be included in the results of a query. You can use this function to exclude certain fields or to only include specific fields. For example:

Model.find({}).select({ field1: 1, field2: 1 });

These functions can be chained together to create more complex queries. For example:

User.find({})
    .limit(10)
    .sort({ age: -1 })
    .select("age name")
    .then((users) => {
        console.log(users);

    });

Output:

 

Reference: https://mongoosejs.com/docs/queries.html



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads