Open In App

Mongoose Document Model.insertMany() API

Last Updated : 29 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Model.insertMany() method of the Mongoose API is used to insert more than one document in the collection at a time in one go. We can provide an array of objects to the insertMany() and can be executed on the model object. Mongoose validates all the objects in the array and if any object has a validation error no object or document will get inserted.

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.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this:

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Example 1: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields “name” and “age”. In the end, we are using insertMany() method on the User model which will insert three documents in a single execution. We have created an array of objects which have documents that will be inserted into the User collection.

  • app.js: Write down the below code in the app.js file:

Javascript




// Require mongoose module
const mongoose = require('mongoose');
 
// Set Up the Database connection
mongoose.connect(
    useNewUrlParser: true,
    useUnifiedTopology: true
})
 
const userSchema = new mongoose.Schema(
    { name: String, age: Number }
)
 
// Defining userSchema model
const User = mongoose.model('User', userSchema);
const docs = [{ name: "User4", age: 40 },
    { name: "User5", age: 50 },
    { name: "User6", age: 60 }]
User.insertMany(docs).then(result => {
    console.log(result)
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
  {
    name: 'User4',
    age: 40,
    _id: new ObjectId("6316f866e10eb7753ec68911"),
    __v: 0
  },
  {
    name: 'User5',
    age: 50,
    _id: new ObjectId("6316f866e10eb7753ec68912"),
    __v: 0
  },
  {
    name: 'User6',
    age: 60,
    _id: new ObjectId("6316f866e10eb7753ec68913"),
    __v: 0
  }
]

GUI Representation of the Database using Robo3T GUI tool:

 

Example 2: In this example, we have established a database connection using mongoose and defined model over studentSchema, having three columns or fields “name”, “school”, and “class”. In this example, we are trying to insert two documents in a single execution, but the value of the “class” field (first object of array) does not match with the type defined in the schema which will cause a validation error and no document will get inserted in the database. In the result, you will get a validation error and in the database, no document will be inserted.

  • app.js: Write down the below code in the app.js file:

Javascript




// Require mongoose module
const mongoose = require("mongoose");
 
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
const studentSchema = new mongoose.Schema({
    name: String,
    school: String,
    class: Number,
});
 
// Defining studentSchema model
const Student = mongoose.model("Student", studentSchema);
 
Student.insertMany([
    { name: "Student1", school: "ABC", class: "A1" },
    { name: "Student2", school: "ABC", class: "A2" },
]).then((result) => {
    console.log(result);
});


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

UnhandledPromiseRejectionWarning: ValidationError:
Student validation failed: class: Cast to Number failed for value
"A1" (type string) at path "class"

GUI Representation of the Database using Robo3T GUI tool:

 

Reference: https://mongoosejs.com/docs/api/model.html#model_Model-insertMany



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

Similar Reads