2015-05-27 107 views
1

后无法正常使用的NodeJS上的MongoDB +一个简单的脚本一些奇怪的情况。的NodeJS,MongoDB的更新阵列插入许多

我从CSV文件中读取数据,并用数据做操作后,我想将数据保存到MongoDB的。一切工作正常使用单个插入,但有更好的表现,我想用插入很多,所以这里是我的脚本:

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

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中给我的错误后,和缓冲器阵列将包含数据:

[{ 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。有没有可能阻止这种情况? 我该如何清除缓冲区变量?

我猜缓存中还有一个已经插入的数据,因为相同的ID是已存在于数据库蒙戈给错误的问题(但我不知道,我右100%)

感谢答复

回答

0

仅当存在数据库中的一些_id文档可能会出现错误,说ID1,而你试图插入其中有ID1作为其_id字段值一个新的文档。

这可能是因为以下几点:

  • 您已经在收集一些文件,并有收集和CSV文件共享相同_id
  • 有只是在一个文件在CSV文件中至少有两行共享相同_id

如果_id字段的值是不适合你的关键,你可以从CSV里读出你的对象删除属性ght在您的JavaScript代码中使用delete

否则,你有冲突,需要决定你想重复_id文件做什么。如果你都OK的方式覆盖,你可以通过具有{upsert: 1}选项,将用新值更新文档中的情况下,如果有一个具有相同_id现有实现这一目标。

+0

更新缓冲区正如你可以从上面的代码看 - 我不是推到_id缓冲,并且csv没有_id字段。 _Id在第一次做insertMany后出现在缓冲区中。 – user1341596

+0

好吧,我明白了。那么什么是'domainystem.domain'? – bagrat

+0

运行错误的数据库 - 更新 – user1341596

0

与封闭的固定缓冲区:

if(buffer.length >= 100 || readAllLines) { 
    (function(buffer) { 
     db.collection('peoples').insert(buffer, ... 
    }) 
    buffer = [] 
} 

但仍然在寻找解决方案 - 如何在不插入