繁体   English   中英

在 updateOne mongoose 方法中更新现有或使用 mongo 运算符的 function

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM