我想在我的用户模型上编写一个“查找或创建”静态方法 – 非常类似于upsert,但预保存挂钩也会运行. 这是我的用户模型: var Promise = require("bluebird")var mongoose = require("mongoose");var bcrypt
这是我的用户模型:
var Promise = require("bluebird")
var mongoose = require("mongoose");
var bcrypt = Promise.promisifyAll(require('bcrypt-nodejs'));
var Schema = mongoose.Schema;
var userSchema = new Schema({
e: { type: String, required: true, trim: true, index: { unique: true } },
fb: { type: String, required: true },
ap: { type: String, required: true },
f: { type: String, required: true },
l: { type: String, required: true }
});
// Execute before each user.save() call
userSchema.pre('save', function(callback) {
bcrypt.genSaltAsync(5)
.then(function (salt) {
return bcrypt.hash(this.fb, salt, null);
})
.then(function (hash) {
user.fb = hash;
})
.then(function (){
return bcrypt.genSaltAsync(5);
})
.then(function (salt) {
return bcrypt.hash(this.ap, salt, null);
})
.then(function (hash) {
user.ap = hash;
})
.then(function () {
callback();
})
.catch(function (err) {
callback(err);
});
});
module.exports = mongoose.model('User', userSchema);
我想要它做这样的事情,但我尝试的是什么工作:
userSchema.statics.FindOrCreate(function(json) {
return this.findOne({e: json.email}, function(err, user) {
if(err) return err;
if(user) return user;
// return new user
});
});
非常感谢!
使用钩子(猫鼬中间件):schema.post('find', function(result) {
// if there is no result
// create new document
});
