Mongoose insertMany() – Insert Multiple Documents to MongoDB
To insert multiple documents to MongoDB using Mongoose, use Model.insertMany(docs, options) in new Node.js code. It accepts an array of document objects, validates them against the Mongoose schema, and inserts them into the mapped MongoDB collection.
Older Mongoose examples may use Model.collection.insert(docs_array, options, callback_function). That style talks directly to the underlying collection and is not the recommended Mongoose model API for new code. This tutorial keeps the original callback example for reference, and also shows the modern insertMany() approach with async/await.
Recommended Mongoose insertMany() syntax for multiple documents
The usual syntax for inserting an array of documents with a Mongoose model is shown below.
Model.insertMany(docs, options)
where
docsis an array of plain JavaScript objects to insert as MongoDB documents.optionsis an optional configuration object. Common options includeorderedandrawResult.- The returned promise resolves to the inserted Mongoose documents by default.
By default, insertMany() uses ordered insert behavior. If validation or a write error occurs, the operation stops according to the ordered insert rules. With { ordered: false }, Mongoose can continue processing valid documents where supported, but your error handling must check which documents succeeded and which failed.
Async/await example to insert multiple books with Mongoose insertMany()
The following Node.js script connects to the tutorialkart database, defines a Book model, and inserts three documents into the bookstore collection using Book.insertMany().
insert-many-books.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 books = [
{ name: 'Mongoose Tutorial', price: 10, quantity: 25 },
{ name: 'NodeJS tutorial', price: 15, quantity: 5 },
{ name: 'MongoDB Tutorial', price: 20, quantity: 2 }
];
const insertedBooks = await Book.insertMany(books);
console.log('Inserted documents:', insertedBooks.length);
insertedBooks.forEach((book) => {
console.log(book.name + ' - ' + book._id.toString());
});
}
main()
.catch((error) => {
console.error('Insert failed:', error.message);
})
.finally(async () => {
await mongoose.connection.close();
});
Run the file using Node.js.
node insert-many-books.js
A successful run prints the number of inserted documents and the generated MongoDB _id values. Your _id values will be different.
Inserted documents: 3
Mongoose Tutorial - 66a0f01d00f5d6a4d32a7121
NodeJS tutorial - 66a0f01d00f5d6a4d32a7122
MongoDB Tutorial - 66a0f01d00f5d6a4d32a7123
Legacy Model.collection.insert() syntax from older Mongoose code
The original example below uses Model.collection.insert(). It is useful for understanding older code, but for a normal Mongoose model insert in current projects, prefer Model.insertMany().
Model.collection.insert(docs, options, callback)
where
- docs is the array of documents to be inserted;
- options is an optional configuration object – see the docs
- callback(err, docs) will be called after all documents get saved or an error occurs. On success, docs is the array of persisted documents.
Example – Insert Multiple Documents to MongoDB via Node.js
In this example, we will write a Node.js script that inserts Multiple Documents to MongoDB Collection 'bookstore' using Mongoose module.
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');
// documents array
var books = [{ name: 'Mongoose Tutorial', price: 10, quantity: 25 },
{ name: 'NodeJS tutorial', price: 15, quantity: 5 },
{ name: 'MongoDB Tutorial', price: 20, quantity: 2 }];
// save multiple documents to the collection referenced by Book Model
Book.collection.insert(books, function (err, docs) {
if (err){
return console.error(err);
} else {
console.log("Multiple documents inserted to Collection");
}
});
});
Open a terminal or command prompt and run this script using node command as shown in the following.
Output
$ node node-js-mongoose.js
Connection Successful!
Multiple documents inserted to Collection
Check MongoDB for the entries in bookstore collection.
> db.bookstore.find()
{ "_id" : ObjectId("5a77033a27e41d271f58fde1"), "name" : "Mongoose Tutorial", "price" : 10, "quantity" : 25 }
{ "_id" : ObjectId("5a77033a27e41d271f58fde2"), "name" : "NodeJS tutorial", "price" : 15, "quantity" : 5 }
{ "_id" : ObjectId("5a77033a27e41d271f58fde3"), "name" : "MongoDB Tutorial", "price" : 20, "quantity" : 2 }
Validation behavior when Mongoose insertMany() inserts many documents
insertMany() validates each document against the schema before writing to MongoDB. If a document fails validation, Mongoose reports the error and the insert may stop depending on the ordered option. This is different from directly using low-level collection methods where you may bypass some Mongoose document features.
const books = [
{ name: 'Valid Mongoose Book', price: 10, quantity: 25 },
{ name: 'Invalid Price Book', price: -5, quantity: 3 },
{ name: 'Valid MongoDB Book', price: 20, quantity: 2 }
];
try {
await Book.insertMany(books);
} catch (error) {
console.error(error.name);
console.error(error.message);
}
In this example, the second document violates the min: 0 validation rule for price. The error message may vary by Mongoose version, but the important point is that invalid data is not silently accepted by the schema.
ValidationError
Book validation failed: price: Path `price` (-5) is less than minimum allowed value (0).
Ordered and unordered inserts with Mongoose insertMany()
The ordered option controls how MongoDB handles errors while inserting multiple documents. Ordered inserts are easier to reason about because the insert process stops when it meets an error. Unordered inserts can be useful for batch imports where you want valid documents to continue even if some documents fail because of validation or duplicate key errors.
| Option | Behavior | When to use |
|---|---|---|
{ ordered: true } | Documents are processed in order and the operation stops on an error. | Use when order and all-or-stop behavior matters. |
{ ordered: false } | MongoDB may continue processing other valid documents after an error. | Use for imports where partial success is acceptable and errors are handled carefully. |
await Book.insertMany(books, { ordered: false });
When using unordered inserts, do not assume that every document was inserted just because some documents were inserted. Always inspect the error or result information in your application logic.
Getting inserted ids after inserting multiple Mongoose documents
By default, Model.insertMany() resolves to an array of inserted Mongoose documents. Each returned document has an _id. This makes it easy to return inserted ids from an API endpoint or log the inserted records.
const insertedBooks = await Book.insertMany(books);
const insertedIds = insertedBooks.map((book) => book._id.toString());
console.log(insertedIds);
If you need native MongoDB driver-style insert result details, check Mongoose options such as rawResult for your installed Mongoose version. For most Mongoose application code, the returned documents are enough.
Mongoose insertMany() vs save() loop vs MongoDB driver insertMany()
For multiple documents, Model.insertMany() is usually clearer than calling save() repeatedly in a loop. It expresses the intent as one batch insert and avoids writing manual loop logic for a simple insert operation.
| Approach | Best use | Important note |
|---|---|---|
Model.insertMany() | Insert many documents with Mongoose schema casting and validation. | Does not run save() middleware. |
document.save() in a loop | Insert documents one by one when each document needs save middleware or per-document processing. | More verbose and usually slower for simple batch inserts. |
MongoDB driver insertMany() | Insert documents without using Mongoose models. | Returns native driver insert result data instead of Mongoose documents. |
If your schema uses pre('save') or post('save') middleware, remember that insertMany() does not trigger save middleware. Use model-level insertMany middleware or insert documents with save() when save hooks are required.
Common mistakes while inserting multiple documents with Mongoose
- Using old collection methods in new code: Prefer
Model.insertMany()overModel.collection.insert()for normal Mongoose model inserts. - Forgetting to await the insert: Use
await Book.insertMany(books)or return the promise from your function. - Ignoring validation errors: Add
try/catchand check why the batch failed. - Assuming unordered inserts are fully successful: With
ordered: false, inspect errors and inserted results before reporting success. - Expecting save middleware to run:
insertMany()does not runsave()middleware. - Unexpected collection name: Pass the collection name as the third argument to
mongoose.model()when you want a specific collection such asbookstore.
Mongoose insertMany() FAQs for MongoDB batch inserts
Which Mongoose method should I use to insert multiple documents?
Use Model.insertMany() for a normal Mongoose batch insert. It accepts an array of objects and inserts them into the collection mapped to the model.
Does Mongoose insertMany() validate every document before insertion?
Yes. Mongoose casts and validates documents based on the schema. If a document fails validation, the insert operation reports an error and behavior depends on options such as ordered.
Does insertMany() run pre save or post save middleware?
No. insertMany() does not trigger save() middleware. If your logic depends on save hooks, use save() for each document or define middleware that is meant for insertMany().
How do I get the _id values after insertMany() in Mongoose?
Store the returned array from await Model.insertMany(docs). Each inserted document in the array has an _id value.
When should I use ordered false with insertMany()?
Use { ordered: false } when you are importing a batch and want valid documents to continue even if some documents fail. Use it only when your code properly handles partial success and error details.
Editorial QA checklist for this Mongoose insertMany() tutorial
- Does the article recommend
Model.insertMany()for current Mongoose code instead of only showing oldModel.collection.insert()usage? - Does the tutorial explain what the
docsarray contains and what the returned inserted documents include? - Does the validation section clearly state how schema rules can stop invalid documents from being inserted?
- Does the ordered vs unordered section warn about partial success handling with
{ ordered: false }? - Does the middleware note prevent readers from assuming that
save()hooks run duringinsertMany()? - Do all examples consistently use the
bookstorecollection and theBookmodel?
Summary of inserting multiple documents to MongoDB using Mongoose
In this Node.js Mongoose Tutorial, we have learnt to insert multiple documents to MongoDB using Mongoose. For new code, use Model.insertMany() with an array of documents, handle the returned promise with await, and check validation or write errors carefully. Use { ordered: false } only when partial success is acceptable and your code can handle the failed documents correctly.
TutorialKart.com