我想在我的用户模型上编写一个“查找或创建”静态方法 - 很像一个 upsert 但预保存钩子(Hook)也将运行。

这是我的用户模型:

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

非常感谢!

最佳答案

使用钩子(Hook)( Mongoose 中间件):

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

关于node.js:如何在我的用户模型上编写 "find or create"静态方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32842114/

10-10 11:06