Mongoose save() – Insert One Document to MongoDB from Node.js
Mongoose save() inserts a new document into MongoDB when you create a model instance and call save() on it. The operation is asynchronous. In current Mongoose code, use await document.save() or handle the returned promise. In older code, you may also see a callback passed to save().
In this tutorial, we shall learn how to insert a single document into a MongoDB collection using the Node.js Mongoose module. We shall also see what save() returns, how the generated _id is available, and how schema validation affects the insert.
How Mongoose save() inserts a document into MongoDB
To insert one document with Mongoose, follow this flow: connect to MongoDB, define a schema, compile a model, create a document instance, and call save(). When the document is new, Mongoose sends an insert operation to MongoDB. If the collection does not already exist, MongoDB creates it when the first document is inserted.
new Model({...})creates a Mongoose document in Node.js memory.document.save()validates the document and writes it to MongoDB.- The saved document contains the generated
_idfield. - Mongoose also adds
__vby default for versioning.
Modern async/await example for inserting a Mongoose document
The following example uses async/await, which is the preferred style for new Mongoose code. It inserts one book document into the bookstore collection and prints the saved document id.
insert-one-book.js
const mongoose = require('mongoose');
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/tutorialkart');
const bookSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
price: {
type: Number,
required: true,
min: 0
},
quantity: {
type: Number,
required: true,
min: 0
}
});
const Book = mongoose.model('Book', bookSchema, 'bookstore');
const book = new Book({
name: 'Introduction to Mongoose',
price: 10,
quantity: 25
});
const savedBook = await book.save();
console.log('Saved book name:', savedBook.name);
console.log('Saved book id:', savedBook._id.toString());
}
main()
.catch((error) => {
console.error('Error while inserting document:', error.message);
})
.finally(async () => {
await mongoose.connection.close();
});
Run the file from the terminal after installing Mongoose and keeping MongoDB available on your local machine.
node insert-one-book.js
A successful run prints the saved document values. The exact _id value will be different on your machine.
Saved book name: Introduction to Mongoose
Saved book id: 66a0d8f57758fdd7c9a7b123
Example 1 – Insert Document to MongoDB using Mongoose save()
The following older callback-style example demonstrates saving a document to a collection. The code is kept as a simple reference for projects that still use callback-based Mongoose patterns.
node-js-mongoose.js
var mongoose = require('mongoose');
// make a connection
mongoose.connect('mongodb://localhost:27017/tutorialkart');
// get reference to database
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
// define Schema
var BookSchema = mongoose.Schema({
name: String,
price: Number,
quantity: Number
});
// compile schema to model
var Book = mongoose.model('Book', BookSchema, 'bookstore');
// a document instance
var book1 = new Book({ name: 'Introduction to Mongoose', price: 10, quantity: 25 });
// save model to database
book1.save(function (err, book) {
if (err) return console.error(err);
console.log(book.name + " saved to bookstore collection.");
});
});
Open a terminal or command prompt and run this script using node command as shown in the following.
$ node node-js-mongoose.js
Connection Successful!
Introduction to Mongoose saved to bookstore collection.
Now check your MongoDB if the document is inserted.
> show collections
bookstore
customers
myNewCollection
people
stores
webpages
> db.bookstore.find()
{ "_id" : ObjectId("5a76f2616204971c6f0456f3"), "name" : "Introduction to Mongoose", "price" : 10, "quantity" : 25, "__v" : 0 }
>
A new collection has been created (as it is not already present), and the document is inserted to the collection.
Getting the generated _id after Mongoose save()
After save() completes successfully, the returned document has the MongoDB _id. You can use this value for logging, redirects, API responses, or follow-up queries. In Mongoose, the _id is usually available on the document instance even before saving, but you should treat the save as successful only after await document.save() resolves without an error.
const savedBook = await book.save();
console.log(savedBook._id);
console.log(savedBook._id.toString());
Schema validation before inserting with Mongoose save()
Mongoose runs schema validation before saving a document. If a required field is missing or a value fails a rule such as min, Mongoose throws a validation error and the document is not inserted. This is one reason save() is useful when you want model-level validation and document middleware.
const invalidBook = new Book({
name: 'Invalid Book',
price: -5,
quantity: 10
});
try {
await invalidBook.save();
} catch (error) {
console.error(error.name);
console.error(error.message);
}
ValidationError
Book validation failed: price: Path `price` (-5) is less than minimum allowed value (0).
Mongoose save() vs create() vs MongoDB insertOne()
Use save() when you already have a document instance and want to persist it. Use Model.create() when you want a shorter model-level helper for creating and saving one or more documents. Use the MongoDB Node.js driver insertOne() when you are not using Mongoose models, schemas, validation, or middleware.
| Method | Best use | What you get back |
|---|---|---|
document.save() | Insert or update a Mongoose document instance with validation and middleware. | The saved Mongoose document. |
Model.create() | Create and save a document directly from plain object data. | The created Mongoose document. |
collection.insertOne() | Insert with the native MongoDB driver without Mongoose schema features. | An insert result that includes insertedId. |
For this tutorial, save() is the right method because the goal is to insert a document using a Mongoose model instance.
Common Mongoose save() insert errors and checks
If the document is not inserted, check the connection string, database name, model name, collection name, and validation rules. In the examples above, the third argument in mongoose.model('Book', bookSchema, 'bookstore') explicitly maps the model to the bookstore collection.
- Connection error: Confirm MongoDB is running and the URI points to the correct host and database.
- ValidationError: Check required fields, number ranges, enum values, and custom validators.
- Unexpected collection name: Pass the collection name as the third argument to
mongoose.model()when you do not want Mongoose to infer a pluralized collection name. - No output after running the script: Make sure the save operation is awaited or handled inside the callback/promise chain.
- Duplicate key error: Check unique indexes such as email, slug, or SKU fields.
Mongoose save() insert document FAQs
Does Mongoose save() insert or update a document?
save() inserts the document when the document is new. If the document already exists and has changes, save() updates it instead.
How do I get the inserted document id in Mongoose?
Store the result of await document.save() and read savedDocument._id. Use savedDocument._id.toString() when you need the id as a string.
Does Mongoose create the collection automatically when saving?
Yes. If the collection does not exist, MongoDB creates it when the first document is inserted. In the example, the bookstore collection is created when the first book document is saved.
Why is __v added to the saved MongoDB document?
__v is Mongoose’s default version key. It helps Mongoose track document versioning. You can configure it in the schema if your application needs a different version key behavior.
Should I use save() or insertOne() for a Node.js MongoDB insert?
Use save() when your code uses Mongoose schemas, models, validation, hooks, or document methods. Use insertOne() when you are using the native MongoDB Node.js driver directly.
Editorial QA checklist for this Mongoose save() tutorial
- Does the tutorial clearly explain that
save()is asynchronous and should be awaited in modern Node.js code? - Does the example show where the
_idof the inserted MongoDB document is available? - Does the article distinguish
save(),Model.create(), and native driverinsertOne()without mixing their return values? - Does the collection name
bookstorematch the model mapping used in the code? - Does the validation section explain why a document may fail before insertion?
Summary of inserting one MongoDB document with Mongoose save()
In this Node.js Mongoose Tutorial, we have learnt to insert document to MongoDB using Mongoose from Node.js. For one document, create a model instance and call save(). The saved document contains the generated _id, and Mongoose runs schema validation before writing the document. In our next tutorial, we shall learn to insert multiple documents to MongoDB using Mongoose.
TutorialKart.com