Open In App

Mongoose insertMany() Function

Last Updated : 14 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection.

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.

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: You can visit the link Install Mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Project Structure:

NodeProj

The updated dependencies in package.json file will look like:

"dependencies": {
"mongoose": "^7.6.5",
}

Example: Below the code example for the insertMany() method:

Javascript




const mongoose = require('mongoose');
 
// Database connection
mongoose.connect(
    {
        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

Output of above command

After running above command, your 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 Robo3T GUI tool as shown below: Database

So this is how you can use mongoose insertMany() function to insert multiple documents into the collection in MongoDB and Node.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads