Open In App

Mongoose save() Function

The `save()` function in Mongoose serves the purpose of persisting a document in the MongoDB database. By invoking this function, you can add new documents to the database or update existing ones. It facilitates the process of storing the document, along with its associated data, in the designated MongoDB collection, making the information persistent and accessible for future retrieval and queries.

Syntax:



document.save(callback)

Parameters:

Steps to Installation of Mongoose Module:

Step 1:You can install this package by using this command.



npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"mongoose": "^7.6.5",
}

Example: Below the code example for the save() method:




const mongoose = require('mongoose');
 
// Database Connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
 
// User model
const User = mongoose.model('User',{
    name: { type: String },
    age: { type: Number }
});
 
var new_user = new User({
    name: 'Manish',
    age:34
})
 
new_user.save(function(err,result){
    if (err){
        console.log(err);
    }
    else{
        console.log(result)
    }
})

Steps to run the program:

node index.js

Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:

Output:

After the function is executed, You can see in the database that the new_user is saved as shown below:

So this is how you can use the mongoose save() function which saves the document to the database. Using this function, new documents can be added to the database.


Article Tags :