如何使用 updateOne 在 MongoDB 中使用其先前值来更新字段

问题描述 投票:0回答:1

我尝试使用 updateOne 更新文档,但代码出现错误,无法访问先前的值来更新字段。出现类型转换错误。使用 Mongoose 7.0.1 版本

invoiceSchema.updateOne({ appointmentId: convertIntoMongoId(invoiceDetail.appointmentId) },
                    {
                        $set: {
                            $inc: { pendingAmount: response.purchase_units[0].payments.captures[0].amount.value },
                            pendingAmount: { $subtract: ['$pendingAmount', response.purchase_units[0].payments.captures[0].amount.value] },
                            status: {
                                $cond: [
                                    {
                                        $and: [
                                            { $gt: ['$paidAmount', 0] },
                                            { $ne: ['$paidAmount', '$totalPayableAmount'] }
                                        ],


                                    },
                                    "Partially Paid",
                                    "Not Paid",
                                ]
                            }
                        }
                    }

                )
            }

{
    "error": {
        "error": {
            "stringValue": "\"{ '$subtract': [ '$pendingAmount', '15.00' ] }\"",
            "valueType": "Object",
            "kind": "Number",
            "value": {
                "$subtract": [
                    "$pendingAmount",
                    "15.00"
                ]
            },
            "name": "CastError",
            "message": "Cast to Number failed for value \"{ '$subtract': [ '$pendingAmount', '15.00' ] }\" (type Object) at path \"pendingAmount\""
        }
    },

}
mongodb mongoose mongodb-query aggregation-framework mongoose-schema
1个回答
0
投票

您需要使用通过聚合管道进行更新。简而言之,将

$set
阶段括在方括号
[]
中以表示聚合管道。这会将
$pendingAmount
转换为该字段的值,而不是文字字符串
$pendingAmount
,如下所示:

invoiceSchema.updateOne({ appointmentId: convertIntoMongoId(invoiceDetail.appointmentId) },
    [
        {
            $set: {
                $inc: { pendingAmount: response.purchase_units[0].payments.captures[0].amount.value },
                pendingAmount: { $subtract: ['$pendingAmount', response.purchase_units[0].payments.captures[0].amount.value] },
                status: {
                    $cond: [
                        {
                            $and: [
                                { $gt: ['$paidAmount', 0] },
                                { $ne: ['$paidAmount', '$totalPayableAmount'] }
                            ],


                        },
                        "Partially Paid",
                        "Not Paid",
                    ]
                }
            }
        }
    ]
);
© www.soinside.com 2019 - 2024. All rights reserved.