Node.js: How can I write a static “find or create” method in my user model?

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

// 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);

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;
        // return new user
    });
});

Many thanks!

+4
source share
2 answers

I recommend skipping Mongoose and using the mongodb promise with async / wait and babel. It will be much simpler and looks something like this:

// 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;
}
0
source

Use hooks (middleware for mongoose):

schema.post('find', function(result) {
    // if there is no result
    // create new document
});
0

Source: https://habr.com/ru/post/1609458/


All Articles