I want to insert/create multiple documents in mongodb using mongoose in nodejs.
Now even if some of the inserts fail may be due to duplicate key the others should be inserted and finally I should have a output which shows inserted and non inserted data array.
example input document:[
{_id: 11, name:'abc'},
{_id: 22, name:'abc'},
{_id: 11, name:'qwe'},
{_id: 33, name:'xyz'}
]
In this the third data is having a duplicate _id and hence will be a error [id dup key: { _id: "11" }]
and the operation will stop with error.
But I want that it should not stop but insert other correct data
expected output is insert: [
{_id: 11, name:'abc'},
{_id: 22, name:'abc'},
{_id_ dup key: { _id: "11" }},
{_id: 33, name:'xyz'}
]
I have tried both
mongoose.model(student).create(_req.body)
mongoose.model(student).insertMany(_req.body)
But both ways failed and throws error. Works correct if all passed data to be created is correct.
Is there any additional property needs to be passed to achieve the same because in official document of mongoose its says it can be as far as i can understand. Also tried passing some options but failed.
https://mongoosejs.com/docs/api/model.html#Model.create()
https://mongoosejs.com/docs/api/model.html#Model.insertMany()
2
Answers
using insertMany(_req.body,{ordered: false,writeConcern:{}})
with this options does the work but throws an error and then in error we can get the output summary.
Though this serves my purpose but If anyone knows any better approach, can surely post your answer.
hope this one will help you