I want to write a static "find or create" method in my user model - pretty much similar to upsert, but pre-capture will also be performed.
This is my user model:
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 }
});
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);
I want him to do something like this, but am not trying anything to work:
userSchema.statics.FindOrCreate(function(json) {
return this.findOne({e: json.email}, function(err, user) {
if(err) return err;
if(user) return user;
});
});
Many thanks!
source
share