Javascript 猫鼬。保存呼叫非常慢

Javascript 猫鼬。保存呼叫非常慢,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,Mongoose Model.save需要约1.5秒以上的时间才能完成,如果我使用Model.collection.insert方法,则只需约50毫秒 除非我弄错了,否则第二种解决方案的速度更快,因为它使用本机mongoDb驱动程序。我曾尝试使用console.time来隔离延迟的位置及其在调用Model.prototype.save函数之前发生的情况,这非常奇怪 auth.username已编制索引,因此不会导致速度缓慢 下面是一个模型模式的示例,以及我如何调用一个新模型 我正在使用mongo

Mongoose Model.save需要约1.5秒以上的时间才能完成,如果我使用Model.collection.insert方法,则只需约50毫秒

除非我弄错了,否则第二种解决方案的速度更快,因为它使用本机mongoDb驱动程序。我曾尝试使用console.time来隔离延迟的位置及其在调用Model.prototype.save函数之前发生的情况,这非常奇怪

auth.username已编制索引,因此不会导致速度缓慢

下面是一个模型模式的示例,以及我如何调用一个新模型

我正在使用mongoose的3.20.0和mongoDB的2.6.4

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

});

原因是“预存”呼叫并将盐系数设置为高:

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

});
userSchema.pre('save',函数(下一步){
//仅当密码已被修改(或是新密码)时才对其进行哈希运算
如果(!this.isModified('auth.password'))返回next();
var user=this;
//生盐

bcrypt.genSalt(14/*您实际上是如何计时的?您实际上是在考虑初始数据库连接吗?POST请求的响应时间是1.5秒以上,如果是初始数据库连接,则在之后立即再次执行相同的请求也可以,但这是一样的。我使用的是console.time('label')>console.timeEnd('label'))检查延迟的位置。这不是很有用。有人问了你一个特定的问题。修改你的问题,以准确显示你是如何衡量你声称的响应的。这给了我们一些可以处理的东西,而你现在的问题没有。找到原因,实际上与我使用盐因子的“预存”模型调用有关对用户密码的哈希值为14,很惊讶10和14之间的差异有多大。很抱歉浪费您的时间@Neillun这让我很痛苦!谢谢!我使用了
genSalt(16)
和操作突然花费了
~20000ms
!genSalt
值中的这一简单更改为我造成了db写入的巨大时间差。感谢您指出这一点!