Skip to content
Related Articles

Related Articles

Mongoose Queries

View Discussion
Improve Article
Save Article
  • Last Updated : 25 May, 2022
View Discussion
Improve Article
Save Article

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:

  • Model.deleteMany(): This query takes the parameters of any field that matches and then deletes all the entries in the database that matches.
  • Model.deleteOne():  This query takes the parameters of any field that matches and then deletes any one of the entries in the database that matches.
  • Model.find(): This query takes the parameters of one or more fields that match and then returns all the entries in the database that matches.
  • Model.findById(): This query takes the id as the parameter and then returns the entry in the database if it exists matches.
  • Model.findByIdAndDelete(): This query takes the id as the parameter and then deletes the entry in the database if it exists matches.
  • Model.findByIdAndRemove(): This query takes the id as the parameter and then removes the entry in the database if it exists and then returns it to the callback function.
  • Model.findByIdAndUpdate(): This query takes the id and the update parameters and values as the parameter and then updates the entry in the database if it exists.
  • Model.findOne(): This query takes the parameters of any field that matches and then returns any one of the entries in the database that matches.
  • Model.findOneAndDelete(): This query takes the parameters of any field that matches and then returns and deletes any one of the entries in the database that matches.
  • Model.findOneAndRemove(): This query takes the parameters of any field that matches and then returns and removes any one of the entries in the database that matches.
  • Model.findOneAndReplace(): This query takes the parameters of any field and the replace document and then replaces any one of the entries in the database that matches.
  • Model.findOneAndUpdate(): This query takes the parameters of one or more fields and the updated fields and values and then updates any one of the entries in the database that matches.
  • Model.replaceOne(): This query takes the parameters as a filter and the replacement document and then replaces any one of the entries in the database that matches.
  • Model.updateMany(): This query takes the parameters as a filter and the updating fields and values and then updates all of the entries in the database that matches.
  • Model.updateOne(): This query takes the parameters as a filter and the updating fields and values and then updates any one of the entries in the database that matches.

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.

index.js




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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!