node.js:我怎样才能写一个;“查找或创建”;我的用户模型上的静态方法?
我想在我的用户模型上写一个“find或create”静态方法——很像upsert,但也会运行pre-save钩子 这是我的用户模型:node.js:我怎样才能写一个;“查找或创建”;我的用户模型上的静态方法?,node.js,mongoose,Node.js,Mongoose,我想在我的用户模型上写一个“find或create”静态方法——很像upsert,但也会运行pre-save钩子 这是我的用户模型: var Promise = require("bluebird") var mongoose = require("mongoose"); var bcrypt = Promise.promisifyAll(require('bcrypt-nodejs')); var Schema = mongoose.Schema; var userSchema = new
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
});
});
非常感谢 我建议跳过Mongoose,将mongodb promise与async/await和babel一起使用。它将更简单,看起来像这样:
// imports, and connect to db
//...
export async function save(user) {
// qry=... upd=...
let salt = await bcrypt.genSaltAsync(10);
// user.hash=
let res = await mongo.update(qry,upd,{upsert:true});
return res;
}
使用钩子(mongoose中间件):
schema.post('find', function(result) {
// if there is no result
// create new document
});