gpt4 book ai didi

node.js - 使用 Mongoose 其他行为更新 $inc 然后 MongoDB 更新

转载 作者:IT老高 更新时间:2023-10-28 12:30:44 27 4
gpt4 key购买 nike

我尝试使用 mongoose 更新文档,但失败了。我可以直接在Mongo中成功执行的查询是这样的:

db.orders.update(
{
orderId: 1014428,
'delivery.items.id': '5585d77c714a90fe0fc2fcb4'
},
{
$inc: {
"delivery.items.$.quantity" : 1
}
}
)

当我尝试使用 mongoose 运行以下更新命令时:

this.update(
{
orderId: this.orderId ,
"delivery.items.id": product.id
},
{
$inc: {
"delivery.items.$.quantity" : 1
}
}, function (err, raw) {
if (err) {
console.log(err);
}

console.log('The raw response from Mongo was ', raw);
}
);

我看到以下错误:

{ [MongoError: cannot use the part (items of delivery.items.id) to traverse the element ({items: [ { quantity: 1, price: 6.9, name: "Manipulationstechniken", brand: null, id: "5585d77c714a90fe0fc2fcb4" } ]})]
name: 'MongoError',
message: 'cannot use the part (items of delivery.items.id) to traverse the element ({items: [ { quantity: 1, price: 6.9, name: "Manipulationstechniken", brand: null, id: "5585d77c714a90fe0fc2fcb4" } ]})',
index: 0,
code: 16837,
errmsg: 'cannot use the part (items of delivery.items.id) to traverse the element ({items: [ { quantity: 1, price: 6.9, name: "Manipulationstechniken", brand: null, id: "5585d77c714a90fe0fc2fcb4" } ]})' }
The raw response from Mongo was { ok: 0, n: 0, nModified: 0 }

我尝试了很多东西。对此有何建议?

根据要求的架构:

var Order = new Schema({
orderId: Number,
orderDate: String,
customerName: String,
state: Number,
delivery: {
items: {type: Array, default: []},
state: { type: Number, default: 0 }
}
});

最佳答案

TL;DR:在进行更高级的查询时使用您的模型 Order 而不是实例 this:

Orders.update(
{
orderId: this.orderId ,
"delivery.items.id": product.id
},
{
$inc: {
"delivery.items.$.quantity" : 1
}
}, function (err, raw) {
if (err) {
console.log(err);
}

console.log('The raw response from Mongo was ', raw);
}
);

解释:

Model.update()Document.update() 之间的映射差异。

使用模型,则Model.update()将被使用和

Model.update(conditions, doc, options, callback)

将被映射到:

db.collection.update(query = conditions, update = doc, options)

当使用实例而不是调用 Document.update()

Document.update(doc, options, callback)

将映射到以下内容:

db.collection.update(query = {_id: _id}, update = doc, options)

关于node.js - 使用 Mongoose 其他行为更新 $inc 然后 MongoDB 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056980/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com