简体   繁体   English

Express.js和Mongoose:使用bdhash设置默认值(异步)

[英]Express.js & mongoose: set default value with bdhash (async)

How can I set default value (like bdhash which is async) to one field in my mongoose schema? 如何在猫鼬模式中为一个字段设置默认值(例如bdhash是异步的)? Now I see only promise inside. 现在我只看到内心的希望。 But why? 但为什么? Seems that I'm using async/await in a right way. 似乎我正在以正确的方式使用异步/等待 Also I tried to do this in a hook (' validate ') 我也试图在一个钩子中做到这一点(“ 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);

Is it possible to do? 有可能吗? And how? 如何? The best way :) 最好的方法 :)

see http://mongoosejs.com/docs/defaults.html 参见http://mongoosejs.com/docs/defaults.html

Check this example : 检查这个例子:

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');
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM