【发布时间】:2019-01-31 21:30:38
【问题描述】:
我有一个看起来像这样的模型:
fname: String,
lname: String,
rating: [{
rating: {
type: Number,
enum: RATING,
default: 5
},
date: {
type: Date,
default: Date.now
}
}]
我需要通过在 rating array 中添加新对象以及新的评级和日期来对此模型执行更新。我想使用Model.collection 上的bulkwrite 方法来执行此操作,因为我需要启用批量更新,这样我就不必一一更新了。
我创建了一个array bulkUpdateOperations = [] 并循环执行以下操作:
bulkUpdateOperations.push({
'updateOne': {
'filter': {'_id': item.id},
'update': {$push: {rating: {'rating': item.rating, 'date': Date.now}}}
}
});
Person.collection.bulkWrite(bulkUpdateOperations, {orderd: true, w: 1}, callbackfunc);
但没有任何更新。我收到以下回复:
...
...
...
insertedCount: 0,
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: {},
n: 0 }
如果有人帮助我解决这个问题,我将非常感激。
编辑
这是我作为 POST 正文发送以更新记录的数组:
[{
"id": "5b7d4d348151700014d25bdd",
"rating": 1
},{
"id": "5b771d10c1e03e1e78b854c2",
"rating": 1
},{
"id": "5b771d7ac1e03e1e78b854c8",
"rating": 1
},{
"id": "5b7bd75a33f88c1af8585be0",
"rating": 1
},{
"id": "5b814a2322236100142ac9f6",
"rating": 1
}]
这是数据库中的一个示例集合
{
"_id": {
"$oid": "5b7d4d348151700014d25bdd"
},
"status": "ACTIVE",
"fname": "mr. client",
"lname": "good client",
"contact_info": {
"_id": {
"$oid": "5b7d4d348151700014d25bde"
},
"mobile_no": "0011223344",
"phone_no": "11223344"
},
"handlers": [
{
"_id": {
"$oid": "5b7d4d348151700014d25bdf"
},
"date": {
"$date": "2018-08-22T11:47:00.544Z"
},
"id": {
"$oid": "5b7d45fbfb6fc007d8bdc1f4"
}
}
],
"onboarding_date": {
"$date": "2018-08-22T11:47:00.551Z"
},
"rating": [
{
"rating": 5,
"_id": {
"$oid": "5b814a8e22236100142ac9fc"
},
"date": {
"$date": "2018-08-25T12:22:59.584Z"
}
},
{
"rating": 3,
"_id": {
"$oid": "5b814a8e22236100142ac9fb"
},
"date": {
"$date": "2018-08-25T12:24:46.368Z"
}
}
],
"__v": 0
}
编辑
添加upsert: true 作为updateOne 的过滤器会创建一个新文档,其中只有rating 作为其值。
解决方案
替换
'filter': {'_id': item.id},
通过
'filter': {'_id': mongoose.Types.ObjectId(item.id)},
【问题讨论】:
-
@AnthonyWinzlet 但这就是我正在做的事情
-
可能是您的
item.id不正确... -
@AnthonyWinzlet 我再次检查了。我有 5 条记录来测试这个 bulkwrite,并且所有 id 都存在于数据库中
-
你能不能把集合和数组贴出来
标签: node.js mongodb mongoose bulkupdate