Home > Enterprise >  how to create multiple new documents at once in mongoDB with node js
how to create multiple new documents at once in mongoDB with node js

Time:10-10

i want to add some data in mongoDB. here is the code

const data = [{user : "1",password: "1"},
{user : "2",password: "2"},
{user : "3",password: "3"},
// upto 1000
{user : "1000",password: "1000"},]

for(let x=0; x<data; x  ){
const user = new User(data[x])
await user.save()
}

It works, but it takes more than 5 seconds to add data into the MongoDB database. I know this is because of the for loop, so I want to find a way by which all data is added in database at once, like this

const user = new User(data)

please help me to find solution, here is my schema

const UserDetails = new mongoose.Schema({
    user: String,
    password : String,
    hobbies : [{game : String, dance : String}]
    }]
});

CodePudding user response:

Thats Easy! Use Map, it works faster than for-loop. Please research on this later.

const map1 = performance.now()
const result = await Promise.all(data.map(async e => {
    await mapModel.create({ //replace 'mapModel' with your schema name
        user: e.user,
        password: e.password
    })
}));
const map2 = performance.now()

res.send({
    status: "completed",
    map_time: map2 - map1,
})

Above code just takes 18ms ;)

  • Related