通过使用位置运算符,使用feathersjs update函数更新数据时遇到问题。我在mongoDB中有以下JSON文档:
{
"name" : "John Jonson",
"payments" : [
{
"year" : 2016,
"payments" : [
{
"comment" : "",
"title" : "1 payment",
"amount" : 100,
"date" : ISODate("2016-12-20T15:04:09.647Z")
}
]
},
{
"year" : 2015,
"payments" : [
{
"comment" : "first payment",
"title" : "02/04/2015",
"amount" : 150,
"date" : ISODate("2016-12-20T15:10:04.499Z")
},
{
"comment" : "second payment",
"title" : "05/06/2015",
"amount" : 150,
"date" : ISODate("2016-12-20T15:10:04.499Z")
}
]
}
]
}
我尝试通过推送到payment.payments数组来更新此文档,该对象仅存在于2015年年份的对象:
var data = {
_id: "5a16e032b7a982bc9b7bd7fe",
payment: {
"amount": 200,
"title": "09/02/2016",
"comment": ""
}
}
app.service('payments').update({_id: data._id, "payments.year": 2015}, {$push: { "payments.$.payments": data.payment }}, { "multi": true }, (error, result) => {
console.log(error)
console.log(result)
});
在调用上述函数后,我收到以下消息:
"exception: The positional operator did not find the match needed from the query. Unexpanded update: payments.$.payments"
但是当我在mongo shell中使用这个语句时,一切都很好:
db.payments.update({"_id" : ObjectId("5a16e032b7a982bc9b7bd7fe"), "payments.year": 2015}, {$push: { "payments.$.payments": {"amount":200,"title":"09/02/2016","comment":""}}}, {"multi": true});
*我解决了我的问题。我使用补丁方法:*
var query = {_id: data._id, "payments.year": 2015}
app.service('payments').patch(null, {$push: { "payments.$.payments": data.payment }}, { query }, (error, result) => {
console.log(error)
console.log(result)
});
我只有一个问题。为什么上面的代码工作正常,但下面的代码没有?
app.service('payments').patch(null, {$push: { "payments.$.payments": data.payment }}, {_id: data._id, "payments.year": 2015}, (error, result) => {
console.log(error)
console.log(result)
});
答案 0 :(得分:0)
工作代码中的query
使用属性值缩写。羽毛mongodb适配器补丁方法采用query
参数,所以试试这个:
app.service('payments').patch(null, {$push: { "payments.$.payments": data.payment }}, {query: { _id: data._id, "payments.year": 2015 }}, (error, result) => {
console.log(error)
console.log(result)
});