([电子邮件受保护] /cdn-cgi/l/email-protection, [电子邮件受保护] /cdn-cgi/l/email-protection)
TL;DR
await GasStation.collection.bulkWrite([ // <<==== use the model name
{
'updateOne': {
'filter': { 'id': '<some id>' },
'update': { '$set': { /* properties to update */ } },
'upsert': true, // <<==== upsert in every document
}
},
/* other operations here... */
]);
很长的故事:
经过一番挣扎后Mongoose API 文档贫乏 http://mongoosejs.com/docs/api.html#model_Model.bulkWrite,我解决了批量更新插入调整updateOne:{}
操作在bulkWrite()
method.
需要考虑一些未记录的事情:
// suppose:
var GasStation = mongoose.model('gasstation', gasStationsSchema);
var bulkOps = [ ];
// for ( ... each gasStation to upsert ...) {
let gasStation = { country:'a', localId:'b', xyz:'c' };
// [populate gasStation as needed]
// Each document should look like this: (note the 'upsert': true)
let upsertDoc = {
'updateOne': {
'filter': { 'country': gasStation.country, 'localId': gasStation.localId },
'update': gasStation,
'upsert': true
}};
bulkOps.push(upsertDoc);
// end for loop
// now bulkWrite (note the use of 'Model.collection')
GasStation.collection.bulkWrite(bulkOps)
.then( bulkWriteOpResult => {
console.log('BULK update OK');
console.log(JSON.stringify(bulkWriteOpResult, null, 2));
})
.catch( err => {
console.log('BULK update error');
console.log(JSON.stringify(err, null, 2));
});
这里的两个关键问题是 API 文档不完整的问题(至少在撰写本文时):
-
'upsert': true
在每个文档中。 Mongoose API () 中没有对此进行记录,通常指的是节点 mongodb-native司机。看着更新此驱动程序中的一个 http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#updateOne,你可以考虑添加'options':{'upsert': true}
,但是,不……那不行。我还尝试将这两种情况添加到bulkWrite(,[options],)
争论,也没有效果。
-
GasStation.collection.bulkWrite()
。虽然猫鼬的bulkWrite()方法 http://mongoosejs.com/docs/api.html#model_Model.bulkWrite声称它应该被称为Model.bulkWrite()
(在这种情况下,GasStation.bulkWrite()
),这将触发MongoError: Unknown modifier: $__
. So, Model.collection.bulkWrite()
必须使用。
另外,请注意:
You don't need to use the $set
mongo operator in the updateOne.update
field, since mongoose handles it in case of upsert (see bulkWrite() comments in example http://mongoosejs.com/docs/api.html#model_Model.bulkWrite).
- 请注意,我在架构中的唯一索引(更新插入正常工作所需)定义为:
gasStationsSchema.index({ country: 1, localId: 1 }, { unique: true });
希望能帮助到你。
==> 编辑:(猫鼬 5?)
正如@JustinSmith 所注意到的,$set
Mongoose 添加的运算符似乎不再工作了。也许是因为 Mongoose 5?
无论如何,使用$set
明确应该这样做:
'update': { '$set': gasStation },