Open In App

Mongoose Document API

Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose documents correspond to MongoDB documents in a one-to-one relationship. A mongoose document is basically an instance of a model.

You need to first install the mongoose module:

Step 1: You need to visit the link mongoose module. You can install it using this command.

npm install mongoose

Step 2: After that, create a folder and also create a file in that folder, for example, index.js, To run the file using this command.

node index.js

Step 3: Also don’t forget to start the MongoDB server on another terminal tab using this command.

mongod

Now, let’s see how it works:

1. Creating a new document: To create a new document, you need to create a mongoose model, and then using that model, you can create a new document. And to save it to the database, you need to use the save() method to save one document or insertMany() method to insert multiple documents.

Example: In the below example, we are going to create a new document. Open the index.js file and write the below code:

Javascript




const mongoose = require("mongoose");
 
// Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
// User model
const User = mongoose.model("User", {
    name: { type: String },
    age: { type: Number },
});
 
// Creating a new dummy user document
const newUser = new User({
    name: "Ayush",
    age: 20,
});
 
// Save it to the database
newUser.save((err, res) => {
    if (err) return handleError(err);
    else return console.log("Result: ", res)
});
 
// For inserting multiple documents
User.insertMany(
    [
        {
            name: "Rishu",
            age: 21,
        },
        {
            name: "Megha",
            age: 24,
        },
        {
            name: "Aman",
            age: 16,
        },
        {
            name: "Riya",
            age: 18,
        },
    ],
    (err, res) => {
        if (err) return handleError(err);
        else return console.log("Result: ", res)
    }
);


Steps to run the application: Write the below code in the terminal to run the server up:

node index.js

Output: 

create user terminal output

Above is the sample data in the database after the function is executed, You can use MongoDB compass or terminal to see the database:

Mongo Compass Output data

2. Retrieving documents: To retrieve a document we need to use the findOne() method. It takes conditions as a parameter, which is absolutely optional.

Example: In the below example, we are going to retrieve documents. Open the index.js file and write the below code:

Javascript




const mongoose = require('mongoose');
 
// Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true
});
 
// User model
const User = mongoose.model('User', {
    name: { type: String },
    age: { type: Number }
});
 
// Find only one document matching
// the condition(age >= 21)
User.findOne({ age: { $gte: 21 } }, function (err, res) {
    if (err) {
        console.log(err)
    }
    else {
        console.log("Result : ", res);
    }
});


Steps to run the application: Write the below code in the terminal to run the server up:

node index.js

Output: 

findOne Terminal Output

3. Updating a document: To update a document you need to use the updateOne() method or findOneAndUpdate() method. The key difference b/w them is that updateOne() doesn’t return the updated document while findOneAndUpdate() return the updated document.

Example: In the below example, we are going to update documents. Open the index.js file and write the below code:

Javascript




const mongoose = require('mongoose');
 
// Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true
});
 
// User model
const User = mongoose.model('User', {
    name: { type: String },
    age: { type: Number }
});
 
// Update only one document matching
User.updateOne({ name: "Rishu" },
{ age: 22 }, function (err, res) {
    if (err) {
        console.log(err)
    }
});
 
// Or you can use findOneAndUpdate()
 
const doc = User.findOneAndUpdate(
    { name: "Rishu" },
    { age: 22 },
     
    // if 'new' isn't true then findOneAndUpdate()
    // will return the document as it was
    // before it was updated.
     
    { new: true },
    function (err, res) {
        if (err) {
            console.log(err)
        }
        else {
            console.log("Result : ", res);
        }
    });


Steps to run the application: Write the below code in the terminal to run the server up:

node index.js

Output: 

update terminal output

As you can see below, the document is updated:

Mongo Compass Output

4.  Overwriting a document: To overwrite a document we can use replaceOne() method. The ‘replaceOne()’  method takes 2 required parameters, some optional parameters, and a callback function. The first parameter is the document you want to overwrite and the second one is the new document object.

Example: In the below example, we are going to overwrite documents. Open the index.js file and write the below code:

Javascript




const mongoose = require('mongoose');
 
// Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true
});
 
// User model
const User = mongoose.model('User', {
    name: { type: String },
    age: { type: Number }
});
 
// OverWrite a document using `replaceOne()` method
 
User.replaceOne(
    { name: "Rishu" },
    { name: "Raja", age: 19 }, (err) => {
    if (err) return console.error(err);
    else {
        console.log('{ name: "Rishu" } is replaced
            with {name: "Raja", age: 19}')
    }
});


Steps to run the application: Write the below code in the terminal to run the server up:

node index.js

Output:

Terminal overwrite output

As you can see below, the document is overwritten:

Mongo Compass overwrites output

We’ve gone over the most significant mongoose document API so far. There are other APIs accessible, which I will discuss in a future article.



Last Updated : 14 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads