【问题标题】:Conditional operator in mongoose猫鼬中的条件运算符
【发布时间】:2022-01-15 12:17:24
【问题描述】:

我正在尝试有条件地执行两个不同的 mongoose 运算符,但它不会返回任何错误并且无法更新文档。

我的架构:

const CartSchema: Schema<Document<ICart>> = new Schema({
    clientID: { type: String, required: true },
    sourceID: { type: String, required: true },
    items: { type: Array },
    source: { type: String, required: true },
}, { collection: "carts", timestamps: true });

我尝试实现的方式:

await CartModel.findOneAndUpdate(
    { sourceID: clientID, 'items.id': Types.ObjectId(itemID) }, 
    { 
         $cond: { 
              if: {
                  $eq: 1,
              },
              then: { $pull: { 'items.$.id': Types.ObjectId(itemID) }},
              else: { $inc: { 'items.$.amount': -1 }},
         }
    }, 
    { new: true }
).lean({ virtuals: true })

我也尝试过这种查询:{ sourceID: clientID },但没有帮助。我想也许我找不到元素,它只是默默地通过。

我要做的主要想法是 - 有一个有条件的猫鼬请求,如果字段amount 中的当前值等于1,我将从数组中删除对象,或者递减-1 的值。

【问题讨论】:

  • 你不能将更新操作符与聚合操作符混合使用,如果你想要一些你不能用普通更新操作符做的事情,只使用管道和聚合操作符的更新。如果您需要$cond,然后使用[...] 使其成为管道更新,在猫鼬中找到一个接受管道作为参数的方法或发送runCommand(更新命令),将pull 替换为$filter,并将inc 替换为$add 1 . 查看有关管道更新的文档

标签: mongodb mongoose conditional-operator


【解决方案1】:

显然,$cond 运算符仅在 aggregation 框架中工作,但在我的 Atlas 层中,我无法检查查询是否正常工作,但我想它应该看起来像这样:

           await CartModel.aggregate([
                { $match: {
                    sourceID: clientID, 
                    'items.id': Types.ObjectId(itemID)
                    }
                }, 
                { 
                    $cond: { 
                        if: {
                            $eq: 1,
                        },
                        then: { $pull: { 'items.$.id': Types.ObjectId(itemID) }},
                        else: { $inc: { 'items.$.amount': -1 }},
                    }
                }
            ])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2017-09-29
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多