猫鼬生成用户名预验证钩

时间:2018-07-18 01:12:11

标签: mongoose mongoose-schema

我正在尝试向我的mongo数据库添加功能,以便如果采用用户名,则数据库将生成一个随机整数并将其附加到建议的用户名之后。我正在使用猫鼬包装来完成所有这些工作!我有一个可行的解决方案,但是我觉得有一个更好的方法可以做到这一点(在循环内使用await似乎是一种不好的做法)。任何帮助将不胜感激!

import mongoose from 'mongoose';
import random from 'lodash/random';

const employeeSchema = new mongoose.Schema({
  username: {
    type: String,
    index: { unique: true, dropDups: true }
  },
  name: {
    fname: {
      type: mongoose.Schema.Types.String,
      required: true
   },
    lname: {
      type: mongoose.Schema.Types.String,
      required: true
    }
  },
  isActive: {
    type: Boolean,
    default: true,
    required: true
  },
  lastLoginDate: {
    type: Date
  }

});

employeeSchema.pre('validate', async function handlePreSave() {
  console.log(`pre validate`);

  if (!this.username) {
    this.username = `${this.name.lname}_${this.name.fname}`;

    let doc = await this.constructor.findOne({ username: this.username });
    while (doc) {
      const newUsername = this.username + random(0, 10000);
      this.username = newUsername;
      doc = await this.constructor.findOne({ username: this.username });
   }
 }
});

export default mongoose.model('Employee', employeeSchema);

0 个答案:

没有答案