The save() method in Mongoose is used to store a document into the MongoDB database. Once you create a model instance with the desired data, calling save() will validate it against the schema and then persist it.
Syntax:
document.save([options], [callback])In the above syntax:
- options: An object to configure save behavior (e.g., validateBeforeSave: false).
- callback: A function with the signature (err, document) that executes after the save completes.
Example of Mongoose save() Method
In this example, we'll create a new user document and save it to the database using the Mongoose save() method.
Code Example (index.js):
const mongoose = require('mongoose');
// Database Connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks',{
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
- Ensure MongoDB is running on your machine.
- Save the code in a file called index
.js. - Run the application using the following command
node index.jsBelow is the sample data in the database before the function is executed, We can use any GUI tool or terminal to see the database like we have used the Robo3T GUI tool as shown below: 
Output: 
After the function is executed, We can see in the database that the new_user is saved as shown below: 
In this example:
- Connect to MongoDB: Connects to the local database geeksforgeeks.
- Define a Model: Creates a User model with name and age fields.
- Create a Document: Creates a new user instance in memory.
- Save the Document: Saves the document to the database. Logs error if any, or prints the saved document.
Save() vs updateOne()
Here is the detailed comparison between save() vs updateOne()
save() | updateOne() |
|---|---|
| Works on a document instance | Works on the model directly |
| Can insert new documents | Only updates existing documents |
| Runs schema validation | Skips validation by default (runValidators: true optional) |
| Triggers pre/post save middleware | Does not trigger middleware |
| Slower (fetch + validate + save) | Faster (direct database update) |
| Use when schema compliance and middleware matter | Use for quick, performance-focused updates |