最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用 mongoose 在 updateOne 中使用 $cond?

网站源码admin32浏览0评论

如何使用 mongoose 在 updateOne 中使用 $cond?

如何使用 mongoose 在 updateOne 中使用 $cond?

我想根据之前的值更新mongodb中的一个值,如果

null
(保存为字符串)那么我将把它更新为一个新值,否则我想保持原样。
这是我的代码:

User.updateOne({_id: user._id}, {$set: {
                        deviceId: {$cond: [{$eq: ['null']}, req.body.deviceId, 'null']}
                    }}, null, function (err, res){
                    if (err){
                        return done(err)
                    }else{
                        return done(null, user)
                    }
                })

但是我得到以下错误(我相信这表明我的语法不正确):

CastError: Cast to string failed for value "{ '$cond': [ { '$eq': [Array] }, 'MYDEVICEID', 'null' ] }" (type Object) at path "deviceId"
    at model.Query.exec (D:\X_APP\XAPP_BACKEND\node_modules\mongoose\lib\query.js:4478:21)
    at _update (D:\X_APP\XAPP_BACKEND\node_modules\mongoose\lib\query.js:4330:11)
    at model.Query.Query.updateOne (D:\X_APP\XAPP_BACKEND\node_modules\mongoose\lib\query.js:4229:10)
    at _update (D:\X_APP\XAPP_BACKEND\node_modules\mongoose\lib\model.js:3834:16)
    at Function.updateOne (D:\X_APP\XAPP_BACKEND\node_modules\mongoose\lib\model.js:3770:10)
    at file:///D:/X_APP/XAPP_BACKEND/middlewares/userMiddleware.js:24:32
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

我搜索并看到了许多使用聚合的应用程序,但是否有可能使用我的方法在猫鼬中实现它

updateOne
?如果是,我的申请有什么问题?

回答如下:

$cond
是一个聚合运算符,您不能在简单的更新查询中使用它,

if null (save as string) then I will update it to a new value, otherwise I want to keep it as it is.

如果您正在尝试更新单个字段,我会建议一个简单的方法,

您可以在查询部分检查条件,如果

deviceId
为空则更新新的
deviceId
否则它将忽略更新操作,

await User.updateOne(
  { 
    _id: user._id,
    deviceId: "null"
  }, 
  {
    $set: {
      deviceId: req.body.deviceId
    }
  }, 
  null, 
  function (err, res){
    if (err){
      return done(err)
    }else{
      return done(null, user)
    }
  }
);

其次,根据您的尝试,您可以通过 更新聚合管道 从 MongoDB 4.2 开始,

await User.updateOne(
  { _id: user._id }, 
  [{
    $set: {
      deviceId: {
        $cond: [
          { $eq: ["$deviceId", "null"] },
          req.body.deviceId,
          "null" // or you can use "$deviceId"
        ]
      }
    }
  }], 
  null, 
  function (err, res){
    if (err){
      return done(err)
    }else{
      return done(null, user)
    }
  }
)
发布评论

评论列表(0)

  1. 暂无评论