我正在尝试根据其Id和父文档的Id更新子文档中的特定字段。我是新手,所以我可能误解了mongoDb文档,但据我所知,findOneAndUpdate应该可以工作。我也尝试过update、updateOne和findByIdAndUpdate。我尝试的任何东西都没有成功更新我的对象。
我正在尝试更新savedBeers数组中特定对象中的评分值。
这是我的模型:
{
"_id": {
"$oid": "5c97cf50cc81525a75eb6c19"
},
"email": "email@gmail.com",
"password": "$2b$10$6ixbu2Ka.Zj0eE5kF21MLO6CiMblgu4D6IHiC7Ta52o.cZFMNw1Mm",
"__v": 0,
"savedBeers": [
{
"id": 2,
"comment": null,
"rating": 0
},
{
"id": 4,
"comment": null,
"rating": 0
}
]
}前端:
function addRating(beerId, ratingValue){
let userId= localStorage.userId
console.log(beerId, userId, ratingValue);
$.ajax({
type: "PUT",
url: `/user/${userId}/${beerId}/${ratingValue}`,
success: addRatingSuccess,
error: addRatingError
});
function addRatingSuccess(response) {
console.log("added", response);
}
function addRatingError() {
console.log("error");
}
}后端userController.js:
addRating:(req,res)=>{
console.log(req.params);
req.params.beerId = parseInt(req.params.beerId)
req.params.ratingValue = parseInt(req.params.ratingValue)
db.User.findOneAndUpdate(
{_id: ObjectId(req.params.userId), "savedBeers.id": req.params.beerId },
{ $set: { 'savedBeers.$.rating' : req.params.ratingValue } },
{new:true})
.exec(function (err, doc){
if (err){
console.log(err);
res.json({
"error": err
})
} else {
console.log(doc);
res.json({
doc
})
}
})
}这是我在前端得到的响应:
added
{doc: {…}}
doc:
email: "email@gmail.com"
savedBeers: Array(2)
0: {id: 2, comment: null, rating: 0}
1: {id: 4, comment: null, rating: 0}
length: 2
__proto__: Array(0)
__v: 0
_id: "5c97cf50cc81525a75eb6c19"
__proto__: Object
__proto__: Object以及后端:
{ userId: '5c97cf50cc81525a75eb6c19', beerId: 4, ratingValue: 3 }
{ savedBeers:
[ { id: 2, comment: null, rating: 0 },
{ id: 4, comment: null, rating: 0 } ],
_id: 5c97cf50cc81525a75eb6c19,
email: 'email@gmail.com',
__v: 0 }非常感谢你能抽出时间来。如果还有其他有用的信息,请告诉我。
发布于 2019-03-29 01:35:45
似乎在"{ $set:{ 'savedBeers.$‘:req.params.ratingValue }“中的"savedBeers.$”之后缺少了".rating“。
因此该行应该是"{ $set:{ 'savedBeers.$.rating‘:req.params.ratingValue }“
https://stackoverflow.com/questions/55403441
复制相似问题