【发布时间】:2019-03-30 12:21:00
【问题描述】:
如何将默认值(如异步的bdhash)设置为我的猫鼬模式中的一个字段?
现在我只看到里面的承诺。但为什么?似乎我以正确的方式使用 async/await 。我也尝试在一个钩子中做到这一点('validate')
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
bcrypt = require('bcrypt');
hashIt = async () => {
let pwd = new Date();
pwd = pwd.toUTCString() + Math.random();
return await bcrypt.hash(pwd, Number(process.env.SALT_WORK_FACTOR));
};
const businessSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
unique: 'Please enter a unique business name',
required: 'Please enter a business name'
},
salt: {
type: String,
trim: true,
default: () => {
return hashIt();
},
required: 'Please enter a business salt'
},
created: {
type: Date,
default: Date.now
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
/* Also tried this way
businessSchema.pre('validate', next => {
if (this.salt) {
return next();
}
this.salt = hashIt();
next();
}); */
module.exports = mongoose.model('Business', businessSchema);
有可能吗?如何?最好的方法:)
【问题讨论】:
-
你需要使用
setDefaultsOnInsert选项
标签: javascript node.js express mongoose