3

我正在尝试使用 mongoose 增加 MongoDB 中的数字。但是我在查询阶段就开始失败了。当我// @ts-ignore无声无息地流动时,它的值不会更新。

它抛出的错误是: Type 'number' is not assignable to type 'undefined'

我的架构:

const CartSchema: Schema<Document<ICart>> = new Schema({
    clientID: { type: String, required: true },
    sourceID: { type: String, required: true },
    items: {
        id: { type: Types.ObjectId },
        amount: { type: Number },
        grindHow: { type: String, trim: true },
        grind: Boolean,
        package: { type: String, trim: true },
        price: { type: Number },
        productID: { type: String },
        productName: { type: String },
        totalProduct: { type: Number },
    },
    source: { type: String, required: true },
}, { collection: "carts", timestamps: true });

CartSchema.virtual('cartTotal').get(function() {
    // @ts-ignore
    const self: any = this;
    
    if(self.items && self.items.length) {
        return self.items.reduce((acc: BigNumber, current: any) => acc.plus(current.totalProduct), new BigNumber(0))
    } else {
        return 0
    }
})

我试图实现的方式是:

const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.$.amount': 1 }}).lean({ virtuals: true })

我也试过了updateOne。我想也许它更灵活。

这就是它突出它的地方

4

2 回答 2

3

items不是一个数组,它是一个对象。您应该使用items.amount不是使用items.$.amount. 像这样更改您的查询:

const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.amount': 1 }}).lean({ virtuals: true })
于 2021-12-10T20:05:27.690 回答
2

问题出在那里的两个地方。

我的架构的问题 - 我将其描述为一个对象(感谢@Nenad Milosavlievic)正确的架构是(或接近正确的。欢迎任何关于架构的提示):

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 });

以及我查询该项目的方式的另一个问题。我应该将字符串 ID 转换为ObjectId. 我错过了...

应该是这样的(加上我需要返回更新的值,所以我添加了一个选项{ new: true }):

await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': Types.ObjectId(itemID) }, { $inc: { 'items.$.amount': 1 }}, { new: true }).lean({ virtuals: true })
于 2021-12-10T20:57:30.187 回答