Open In App

Mongoose Query API

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.

Prerequisites:



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:

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


Article Tags :