我正在嘗試使用貓鼬增加 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。我想也許它更靈活。

uj5u.com熱心網友回復:
items不是陣列,它是一個物件。您應該使用items.amount而不是使用items.$.amount. 像這樣更改您的查詢:
const item = await CartModel.findOneAndUpdate({ sourceID: clientID, 'items.id': itemID }, { $inc: { 'items.amount': 1 }}).lean({ virtuals: true })
uj5u.com熱心網友回復:
問題出在那里的兩個地方。
我的架構的問題 - 我將它描述為一個物件(感謝@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 })
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378982.html
