【问题标题】:node.js: How can I write a "find or create" static method on my user model?node.js:如何在我的用户模型上编写“查找或创建”静态方法?
【发布时间】:2015-12-26 19:46:29
【问题描述】:

我想在我的用户模型上编写一个“查找或创建”静态方法 - 很像一个 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 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
    });
});

非常感谢!

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    我建议跳过 Mongoose 并使用带有 async/await 和 babel 的 mongodb-promise。它会简单得多,看起来像这样:

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

    【讨论】:

      【解决方案2】:

      使用钩子(猫鼬中间件):

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-08
        • 2010-10-17
        • 2011-09-05
        • 1970-01-01
        • 2022-01-27
        • 2018-05-23
        • 2017-03-19
        相关资源
        最近更新 更多