【发布时间】:2015-05-27 13:34:57
【问题描述】:
在 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% 正确)
感谢回复
【问题讨论】:
标签: node.js mongodb insert buffer