Mongoose save() Function
Last Updated :
25 Jan, 2024
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:
callback
(optional): A callback function that will run once the execution is completed. It follows the error-first callback pattern.
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:
Javascript
const mongoose = require( 'mongoose' );
useNewUrlParser: true ,
useCreateIndex: true ,
useUnifiedTopology: true
});
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.
Share your thoughts in the comments
Please Login to comment...