Mongoose – Insert Multiple Documents to MongoDB
To insert Multiple Documents to MongoDB using Mongoose, use Model.collection.insert(docs_array, options, callback_function); method. Callback function has error and inserted_documents as arguments.
Syntax of insert() method
</>
Copy
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
</>
Copy
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 }
Conclusion
In this Node.js Mongoose Tutorial, we have learnt to insert multiple documents to MongoDB using Mongoose.