node.js - Nodejs,mongodb 在插入许多后更新数组

标签 node.js mongodb insert buffer

在 Nodejs + mongodb 上使用简单脚本遇到一些奇怪的情况。

我正在从 csv 文件读取数据,在对数据进行操作后,我想将数据保存到 mongodb 中。一次插入一切正常,但为了获得更好的性能,我想使用多次插入,所以这是我的脚本:

parser.on('readable', function(){
 while(record = parser.read()){
   ...
   // Saving data in a buffer
   buffer.push({
     'name': cleared_name,
     'source': source,
     'notes': notes,
     'address': address[0]
   })

   // If buffer is more that 100 or we rich end of csv file - insert data into mongodb
   if(buffer.length >= 100 || readAllLines) {
      db.collection('peoples').insert(buffer, {w: 1, forceServerObjectId: false},  function(err, result) {
        lineCount -= result.insertedCount;

        // Close db connection if we insert all data
        if (lineCount === 0 && readAllLines) {
          db.close()
        }
        // Lets check what is in buffer right now
        console.log(buffer)
        // Clear buffer  
        buffer.length = 0;
        buffer = [] // or delete buffer;
      });
    }
 }
})

插入 200 行后,mongodb 给我这个错误:

 AssertionError: {"name":"MongoError","message":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: databasename.peoples.$_id_ == null ...

缓冲区数组将包含该数据:

[{ name: 'kelly',
source: 'Forbes.com',
notes: 'Scraped from box XX',
address: '104.236.115.138',
_id: 5565c77d8533c30967b5b278 },
{ name: 'kas',
source: 'Forbes.com',
notes: 'Scraped from box XX',
address: '184.168.221.28',
_id: 5565c77d8533c30967b5b279 },
{ name: 'alle',
source: 'Forbes.com',
notes: 'Scraped from box XX',
address: '82.118.66.19',
_id: 5565c77d8533c30967b5b27a }...
]

即使我在插入时将forceServerObjectId设置为false,mongodb也会在缓冲区数组中设置_id。有可能阻止这种情况吗? 我怎样才能确定清除缓冲区变量?

我猜问题是缓冲区仍然包含已插入的数据,并且 mongo 给出错误,因为数据库中已存在相同的 ID(但我不确定我是否 100%正确)

感谢回复

最佳答案

仅当数据库中存在具有某些 _id(例如 ID1)的文档,并且您尝试插入将 ID1 作为其 _id 字段值的新文档时,才会发生此错误。

这可能是由于以下原因:

  • 集合中已有一些文档,并且集合中和 CSV 文件中有一个文档共享相同的 _id
  • CSV 文件中至少有两行共享相同的 _id

如果 _id 字段的值对您来说并不重要,您可以直接在 JavaScript 代码中使用 delete 从从 CSV 读取的对象中删除该属性。

否则,您会遇到冲突,需要决定如何处理重复的 _id 文档。如果您同意覆盖,则可以通过使用 {upsert: 1} 选项来实现这一点,该选项将使用新值更新文档,以防存在具有相同 _id 的文档。

关于node.js - Nodejs,mongodb 在插入许多后更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484103/

相关文章:

javascript - Electron:使用上下文菜单打开

node.js - NodeJS mockgoose 保存模型似乎不起作用

javascript - 为什么 JSON 不支持 NaN 时 MongoDB 允许 NaN 值?

mongodb - 在ubuntu中使用Docker从文件夹还原mongodb dump

php - 在php中的关联多维数组中插入键值对

javascript - JWT 解码返回 "[object Object]"

node.js - Laravel 和 bootstrap glyphicons - 文件复制到哪里,如何设置相对路径以及如何解决 cachebusting?

spring - 如何在 spring data mongodb 存储库中使用限制和跳过?

c++ - 将元素替换为 vector 的特定位置

android - AsyncTask,Insert,在 Android 中选择错误的执行顺序