![](/img/trans.png)
[英]How to query the most recent 5 records in mongoose based on the most recent Ids of reference property
[英]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
列應該跟蹤帳戶中的運行總計。 在路由中,我已經有代碼可以防止用戶提取比賬戶中更多的錢,但我想知道是否可以為我的模型設置以下驗證/掛鈎:
balance
和transactionType
( credit
,如果amount
為正, debit
如果amount
為負)的基礎上欄amount
與前一記錄的balance
(如果存在的話),這樣的記錄可以通過命令簡單地創建new BankAccount({ amount: 100 }).save()
沒有明確說明適當的balance
或transactionType
。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.