如何在猫鼬模式中为一个字段设置默认值(例如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);
有可能吗?如何?最好的方法:)
答案 0 :(得分:0)
请参阅http://mongoosejs.com/docs/defaults.html
检查此示例:
var schema = new Schema({
title: String,
genre: {type: String, default: 'Action'}
});
var Movie = db.model('Movie', schema);
var query = {};
var update = {title: 'The Terminator'};
var options = {
// Create a document if one isn't found. Required
// for `setDefaultsOnInsert`
upsert: true,
setDefaultsOnInsert: true
};
Movie.
findOneAndUpdate(query, update, options, function (error, doc) {
assert.ifError(error);
assert.equal(doc.title, 'The Terminator');
assert.equal(doc.genre, 'Action');
});