Related Articles

Related Articles

Mongoose | insertMany() Function
  • Last Updated : 20 May, 2020

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

Installation of mongoose module:

  1. You can visit the link Install mongoose module. You can install this package by using this command.
    npm install mongoose
  2. After installing mongoose module, you can check your mongoose version in command prompt using the command.
    npm version mongoose
  3. After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
    node index.js

Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have install mongoose module using following command:
    npm install mongoose
  3. Run index.js file using below command:
    node index.js

    Output of above command

  4. 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.js.

My Personal Notes arrow_drop_up
Recommended Articles
Page :