【发布时间】:2017-10-12 11:29:55
【问题描述】:
下面的脚本在 mongo bulkWrite op 语法中有一个错误:$setOnInsert: { count:0 }, 是不必要的,因此 mongo 会抛出异常:“无法同时更新 'count' 和 'count'”。
问题是,node.js 驱动程序似乎没有捕捉到它。此脚本记录“成功!”到控制台。
(async () => {
let db = await require('mongodb').MongoClient.connect('mongodb://localhost:27017/myNewDb');
let mongoOps = [{
updateOne: {
filter: { foo: "bar" },
update: {
$setOnInsert: { count:0 },
$inc: { count:1 },
},
upsert: true,
}
}];
try {
await db.collection("myNewCollection").bulkWrite(mongoOps);
console.log("Success!");
} catch(e) {
console.log("Failed:");
console.log(e);
}
})();
用db.setProfileLevel(2)检查db.system.profile.find({})我们可以看到异常:
{
"op" : "update",
"ns" : "myNewDb.myNewCollection",
"query" : {
"foo" : "bar"
},
"updateobj" : {
"$setOnInsert" : {
"count" : 0
},
"$inc" : {
"count" : 1
}
},
"keyUpdates" : 0,
"writeConflicts" : 0,
"numYield" : 0,
"locks" : {
"Global" : {
"acquireCount" : {
"r" : NumberLong(1),
"w" : NumberLong(1)
}
},
"Database" : {
"acquireCount" : {
"w" : NumberLong(1)
}
},
"Collection" : {
"acquireCount" : {
"w" : NumberLong(1)
}
}
},
"exception" : "Cannot update 'count' and 'count' at the same time",
"exceptionCode" : 16836,
"millis" : 0,
"execStats" : {},
"ts" : ISODate("2017-10-12T01:57:03.008Z"),
"client" : "127.0.0.1",
"allUsers" : [],
"user" : ""
}
为什么驱动程序会吞下这样的错误?我确实看起来像一个错误,但我想我会先在这里问一下以确保。
【问题讨论】:
-
有趣。该错误实际上存在于响应中,但没有引发异常。尽管存在
writeErrors,但响应状态也是ok: 1,这至少给出了在源中查找位置的指示。但这绝对是一个错误。因此,您可以通过检查响应中writeErrors的长度来“解决”问题。但你真的不应该这样做。