亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否可以在模式級別定義使用 mongoose 從另一個字段計算的字段?

是否可以在模式級別定義使用 mongoose 從另一個字段計算的字段?

MMTTMM 2021-10-07 10:35:00
是否可以使用貓鼬模式在模式級別定義基于另一個字段的字段?例如,假設我有一個非常簡單的架構:const mongoose = require('mongoose')const { Schema } = mongooseconst UserSchema = new Schema({  username: {    type: String,    required: true,    unique: true  },  username_lower: {    type: String,    // calculated: this.username.toLowerCase()  },  email: {    type: String,    required: true,    unique: true  },  email_lower: { // for case-insensitive email indexing/lookup    type: String,    // calculated: this.email.toLowerCase()  },  password: {    type: String,    required: true  },  password_acceptable: {    type: Array,    // calculated: [    //    this.password.toLowerCase(),    //    this.password.toUpperCase()    //    this.password.removeWhiteSpace(), // just an example    //  ]  }})const User = mongoose.model('User', UserSchema)module.exports = User是否有類似于虛擬“計算”字段(我已注釋掉)的東西,它允許在保存新文檔時自動創建字段?這將非常方便,并且可以減少必須在我的后端路由上手動定義這些字段的混亂。
查看完整描述

1 回答

?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

您可以通過 Pre 中間件功能來完成,了解更多詳情


UserSchema.pre('save', function(){

   this.username_lower = this.username.toLowerCase();

   this.email_lower = this.email.toLowerCase();

   // and so on ...

   next();

}); 


查看完整回答
反對 回復 2021-10-07
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號