![](/img/trans.png)
[英]Mongo function updateOne doesn't update the field it's suppose to update
[英]Update in function of existing or using mongo operator in updateOne mongoose method
我有一个赞按钮,我希望当用户点击数据库中的赞时:
如果用户还不喜欢它,则增加(如 +1 并从 likeBy 数组中添加用户 ID)
如果用户已经喜欢它,则减少(如 - 1 并从 likeBy 数组中删除使用的 id)
controller:
exports.likeIdea = (req,res,next) => {
const userId = getUserId(req)
Ideas.updateOne({ _id: req.params.id}, {
$set: {
like: {
$cond: [ {$in: [userId, "$likedBy"]}, { $inc: { like: +1 } } , { $inc: { like: -1 } } ]
},
likedBy: {
$cond: [ {$in: [userId, "$likedBy"]}, { $pull: { likedBy: userId } } , { $push: { likedBy: userId } } ]
},
_id: req.params.id
}
})
.then(() => res.status(200).json({ message: 'Success'}))
.catch(error => {
res.status(400).json({ error })
});
};
架构
const ideaSchema = mongoose.Schema({
name: { type: String, required: true},
sumup: { type: String, required: true },
description: { type: String, required: true},
published: {type: Boolean, required: true},
like: {type: Number, required: true},
likedBy: {type: [String]},
author: {type: String, required: true},
dislike: {type: Number, required: true},
dislikedBy: {type: [String]},
imgUrl: {type: String, required: true}
});
CastError: Cast to Number 值失败 "{ '$cond': [ { '$in': [Array] }, { '$inc': [Object] }, { '$inc': [Object] } ] } " 在路径 "like" [...] {messageFormat: undefined, stringValue: '"{
'$cond': [ { '$in': [Array] }, { '$inc': [Object] }, { '$inc': [Object] } ] }"', kind: 'Number', 值:{...},路径:'喜欢',...}
常规更新查询不允许使用内部字段和聚合运算符,如$cond
,因此您不能使用常规更新查询执行此操作,
您可以尝试使用从 MongoDB 4.2 开始的聚合管道进行更新,
$inc
您可以在聚合更新中使用$add
运算符$pull
您可以使用$filter
删除特定用户$push
您可以使用$concatArrays
运算符exports.likeIdea = (req,res,next) => {
const userId = getUserId(req)
Ideas.updateOne({ _id: req.params.id},
[{
$set: {
like: {
$cond: [
{ $in: [userId, "$likedBy"] },
{ $add: ["$like", 1] },
{ $add: ["$like", -1] }
]
},
likedBy: {
$cond: [
{ $in: [userId, "$likedBy"] },
{
$filter: {
input: "$likedBy",
cond: { $ne: ["$$this", userId] }
}
},
{ $concatArrays: ["$likedBy", [userId]] }
]
}
}
}]
).then(() => res.status(200).json({ message: 'Success'}))
.catch(error => {
res.status(400).json({ error })
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.