0

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}]
    }]
});

1 Answer 1

1

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 ;)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.