用Mongoose的其他行为更新$ inc,然后MongoDB更新

我尝试用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 } 

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

按照要求的架构:

 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而不是实例:

 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()和

 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) 

不知道这是否有帮助,但是在这个问题上 ,OP与mongoose3.6.15有类似的问题,并声称它是在3.8.22

编辑:在链接的问题,OP有以下​​工作MongoDB

 db.orchards.update( ({"orchardId": ObjectId("5391c137722b051908000000")}, {"trees" : { $elemMatch: {"name":"apple"}}}), { $push: { "trees.$.fruits": ObjectId("54c542c9d900000000001234") }}) 

但是这不适用于mongoose:

 orchards.update( ({"orchardId": ObjectId.fromString(orchard.id)}, {"trees" : {$elemMatch: {"name": "apple"}}}), {$push: {"trees.$.fruits": ObjectId("54c542c9d900000000001234") }},function(err, data){ ... 

他在评论中说,这个问题已经解决了,转而使用mongoose3.8.22