如何在 nodejs 中使用 mongoose 在 mongodb 中一次创建多个文档。即使有些失败,也应该插入休息,输出应该是摘要

How to create multiple documents at once in mongodb using mongoose in nodejs. Even If some fails rest should be inserted and output should be summary

提问人:Vishal Gupta 提问时间:11/8/2023 更新时间:11/8/2023 访问量:31

问:

我想在nodejs中使用mongoose在mongodb中插入/创建多个文档。 现在,即使某些插入失败可能是由于重复的键,也应该插入其他的,最后我应该有一个输出,显示插入和未插入的数据数组。

    example input document:[
{_id: 11, name:'abc'},
{_id: 22, name:'abc'},
{_id: 11, name:'qwe'},
{_id: 33, name:'xyz'}
]

在这种情况下,第三个数据具有重复的_id,因此将出现错误 [id dup key: { _id: “11” }] 并且操作将因错误而停止。 但我希望它不应该停止,而是插入其他正确的数据

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)

但是两种方式都失败了,并抛出了错误。如果要创建的所有传递数据都正确,则工作正确。是否有任何额外的属性需要传递才能实现相同的目的,因为在猫鼬的官方文件中,它说它可以是我能理解的。还尝试传递一些选项,但失败了。https://mongoosejs.com/docs/api/model.html#Model.create(https://mongoosejs.com/docs/api/model.html#Model.insertMany()

InsertMany API

create API

node.js mongodb 猫鼬 插入 bulkinsert

评论


答:

0赞 Vishal Gupta 11/8/2023 #1

Output

用:

insertMany(_req.body, { ordered: false, writeConcern: {} })

使用此选项可以完成工作,但会抛出错误,然后出错,我们可以获得输出摘要。

虽然这符合我的目的,但如果有人知道任何更好的方法,肯定可以发布您的答案。

0赞 sourav jana 11/8/2023 #2

希望这个能帮到你

const documentsToInsert = [
  {_id: 11, name:'abc'},
  {_id: 22, name:'abc'},
  {_id: 11, name:'qwe'},
  {_id: 33, name:'xyz'}
];

YourModel.insertMany(documentsToInsert, (error, insertedDocuments) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Successfully inserted documents:', insertedDocuments);

    const successfulInserts = insertedDocuments.filter(doc => doc instanceof YourModel);
    const failedInserts = insertedDocuments.filter(doc => !(doc instanceof YourModel));

    console.log('Successfully inserted count:', successfulInserts.length);
    console.log('Failed insert count:', failedInserts.length);
  }