簡體   English   中英

基於表中最新記錄的貓鼬驗證/掛鈎(如果存在)| 銀行賬戶模型

[英]Mongoose Validations/Hooks based on most recent record in table (if exists) | Model for a Bank Account

我正在設計一個銀行賬戶架構,如下所示:

const bankAccountSchema = new mongoose.Schema({
    transactionType: {
        type: String,
        enum: ['credit', 'debit']
        required: true
    },
    amount: {
        type: Number,
        required: true
    },
    balance: {
        type: Number,
        min: 0,
        required: true
    }
}, {
    timestamps: true
})

const BankAccount = mongoose.model('BankAccount', bankAccountSchema)

就用戶而言,他們只能從帳戶中添加或刪除amount (正數或負數)。 balance列應該跟蹤帳戶中的運行總計。 在路由中,我已經有代碼可以防止用戶提取比賬戶中更多的錢,但我想知道是否可以為我的模型設置以下驗證/掛鈎:

  1. 之前保存,自動更新balancetransactionTypecredit ,如果amount為正, debit如果amount為負)的基礎上欄amount與前一記錄的balance (如果存在的話),這樣的記錄可以通過命令簡單地創建new BankAccount({ amount: 100 }).save()沒有明確說明適當的balancetransactionType
  2. 應該無法提取超過賬戶可用的金額,即如果前一個記錄的balance為 100,那么新記錄的amount永遠不會低於 -100。

(1) 和 (2) 都需要在保存之前訪問表中的前一條記錄(如果存在)。 這可以完成還是我必須完全依賴於我的驗證路線?

是的,這是可能的。 Mongoose現在提供了some middlewares/hooks來驗證您的schema 根據您的要求,您可以使用schema.pre hook 它將在saving記錄之前執行。

這是一個例子

const schema = new Schema(..);
schema.pre('save', function(next) {
 if (foo()) {
   console.log('calling next!');
   // `return next();` will make sure the rest of this function doesn't run
   /*return*/ next();
 }
   // Unless you comment out the `return` above, 'after next' will print
   console.log('after next');
});

您可以在此處閱讀有關middlewares更多信息

我使用async驗證器和this.constructor關鍵字解決了這個問題,如下所示:

const bankAccountSchema = new mongoose.Schema({
    transactionType: {
        type: String,
        enum: ['credit', 'debit']
        required: true
    },
    amount: {
        type: Number,
        required: true
    },
    balance: {
        type: Number,
        min: 0,
        required: true,
        async validate(balance) {
            // Make DB calls here
            console.log(await this.constructor.countDocuments())
        }
    }
}, {
    timestamps: true
})

const BankAccount = mongoose.model('BankAccount', bankAccountSchema)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM