Open In App

Mongoose Queries

Mongoose is a MongoDB object modelling and handling for node.js environment.

Mongoose Queries are different static helper functions to carry out CRUD (Create Read Update and Delete) operations which are very important for any database. The static helper functions return a mongoose query object. The mongoose query is carried out first asynchronously and then calls the callback function passed to it. An alternative way is to use the synchronous function which is responsible for executing the query.



Syntax: Call any query function to get the query object as follows on a model:

const Student = mongoose.model('Student', studentSchema);

Student.findOneAndUpdate({ name: 'John' }, 
  function (err, student) {
    if (err) return handleError(err);
    else{
      // Updated successfully
    }
});

The following are different Queries:



Creating Application and Installing Module: We will create a Student model that will contain the fields name, age and date of birth. Then we will save three documents to MongoDB using mongoose. Finally, we are going to update them if their age is greater than 12. Node.js and NPM are used in this example, so it is required to be installed.

Step 1: Create a folder and initialize it:

npm init

Step 2: Install mongoose in the project.

npm i mongoose

Project Structure: The project structure is as follows:

 

Example: Create a schematype, then a model, and create three different documents with some values. Then call the save function to save the document. We can create a save function to save student documents rather than creating individual documents. Then we will call a function that will query the documents having age greater than or equal to 12. We will make them study in high school as a field highschool=true.




const mongoose = require("mongoose");
  
// Database connection
  
// Creating Schema
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: { type: Number, default: 8 },
    highschool: { type: Boolean, default: false },
});
  
// Student model
const Student = mongoose.model("Student", studentSchema);
// Creating Student document from Model
  
// function to save in database
const saveStudent = async (name, age) => {
    let s = new Student({
        name: name,
        age: age,
    });
    await s.save();
    console.log("student document saved in database\n
        Student name:", s.name);
};
  
const updateHighSchool = async () => {
    await Student.updateMany(
        { age: { $gt: 12 } }, 
        { highschool: true });
    console.log("Updated student fields");
};
  
const start = async () => {
    await saveStudent("Ajay", 5);
    await saveStudent("Rajesh", 13);
    await saveStudent("Manav", 15);
    updateHighSchool();
};
  
start();

Step 4: Now run the code using the following command in the Terminal/Command Prompt to run the file.

node index.js

Output:

 

The documents in the MongoDB are as follows: Two students are in high school but not Ajay. Previously all were set to false but two of them got updated.

 

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


Article Tags :