Mongoose insertMany() Function
The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection. This function is efficient and can significantly speed up the process of adding multiple documents compared to inserting each document individually.
Syntax:
Model.insertMany()
Parameters: The Model.insertMany() method accepts three parameters:
- docs: It is an array of objects which will be inserted into the collection.
- options: It is an object with various properties.
- callback: It is a callback function that will run once execution is completed.
Options:
- ordered: (boolean) If true, MongoDB will insert the documents in the order they are given and stop inserting at the first error encountered. If false, MongoDB will insert all documents even if some of them fail (default is true).
- rawResult: (boolean) If true, the function returns the raw result from MongoDB (default is false).
Returns: The Model.insertMany() function returns a promise. The result contains an array of objects having details of documents inserted in the database.
Steps to Installation of Mongoose Module
Step 1: First init the node app using the below command.
npm init -y
Step 2: You can visit the link Install Mongoose module. You can install this package by using this command.
npm install mongoose
Step 3: 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 insertMany() method:
const mongoose = require('mongoose');
// Database connection
mongoose.connect(
'mongodb://127.0.0.1:27017/w3wiki',
{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model(
'User',
{
name: { type: String },
age: { type: Number }
});
// Function call
User.insertMany([
{ name: 'Gourav', age: 20 },
{ name: 'Kartik', age: 20 },
{ name: 'Niharika', age: 20 }
]).then(function () {
console.log("Data inserted") // Success
}).catch(function (error) {
console.log(error) // Failure
});
Steps to run the program:
node index.js
After running the above command, you can see the data is inserted into the database. You can use any GUI tool or terminal to see the database like I have used the Robo3T GUI tool as shown below:
So this is how you can use the Mongoose insertMany() function to insert multiple documents into the collection in MongoDB and Node.