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.
Installation of mongoose module:
- You can visit the link Install mongoose module. You can install this package by using this command.
npm install mongoose
- After installing mongoose module, you can check your mongoose version in command prompt using the command.
npm version mongoose
- 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
const mongoose = require('mongoose'); // Database connection useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Function callUser.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:
- The project structure will look like this:

- Make sure you have install mongoose module using following command:
npm install mongoose
- Run index.js file using below command:
node index.js

- 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:

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


Please Login to comment...