Mongoose .save通话非常慢

时间:2015-01-24 00:18:16

标签: javascript node.js mongodb mongoose

Mongoose Model.save正在接管~1.5 +秒完成,如果我使用Model.collection.insert方法而不是它只有~50ms

第二种解决方案,除非我错了,因为它使用本机mongoDb驱动程序只会更快。我已经尝试使用console.time来隔离延迟的位置,并在调用Model.prototype.save函数之前发生这种情况,这真的很奇怪。

auth.username已建立索引,因此不应导致速度缓慢。

下面是模型架构的示例以及我如何调用新模型。

我使用3.20.0的mongoose和2.6.4的mongoDB。

var userSchema = new Schema({

active: { type: Boolean, default: true },

player_id: ObjectId,
player: mongoose.Schema.Types.Mixed,

auth: {
    token: { type: String, required: true, default: 'temp' },
    username: { type: String, required: true, trim: true, lowercase: true, index: { unique: true } },
    password: { type: String, required: true },
    login_attempts: { type: Number, required: true, default: 0 },
    locked_until: { type: Number } ,
},

contact: {
    first_name: String,
    last_name: String,
    nick_name: String,
    email: { type: String, required: true, trim: true, lowercase: true, index: { unique: true } },
    phone: { type: String, required: false, trim: true, index: { unique: true, sparse: true } }
},

},{collection: 'user' });



-v-v-v-v-v-v-v-v-v-v-v-v-



var mongoose        = require('mongoose'),
    User            = mongoose.model('User');

var newUser = new User(data);

newUser.save(function (err) {

    if(err) { return cb(err); }
    // Call takes ~1.5+ seconds

});

User.collection.insert(data, function(err, user){

    if(err) { return cb(err); }
    // Call takes ~50ms

});

1 个答案:

答案 0 :(得分:2)

事业是一个“预言”。调用盐并将盐因子设置为高:

userSchema.pre('save', function(next) {

// only hash the password if it has been modified (or is new)
if (!this.isModified('auth.password')) return next();

var user = this;

// generate a salt
bcrypt.genSalt(14 /*<< Setting to 14 from 10 caused call to be 10x slower */, function(err, salt) {
    if (err) return next(err);

    // hash the password using our new salt
    bcrypt.hash(user.auth.password, salt, function (err, hash) {
        if (err) return next(err);

        // set the hashed password back on our user document
        user.auth.password = hash;
        next();
    });
});

});