Mongoose insertMany() Function
Last Updated :
14 Jan, 2024
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:
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' );
mongoose.connect(
{
useNewUrlParser: true ,
useCreateIndex: true ,
useUnifiedTopology: true
});
const User = mongoose.model(
'User' ,
{
name: { type: String },
age: { type: Number }
});
User.insertMany([
{ name: 'Gourav' , age: 20 },
{ name: 'Kartik' , age: 20 },
{ name: 'Niharika' , age: 20 }
]).then( function () {
console.log( "Data inserted" )
}). catch ( function (error) {
console.log(error)
});
|
Steps to run the program:
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...