Node.js 为什么mongoose中的.pre会在下次运行之前阻止访问记录?
最近我一直在用nodejs测试mongoose,我对下面代码的行为有点困惑 在用户数据库中Node.js 为什么mongoose中的.pre会在下次运行之前阻止访问记录?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,最近我一直在用nodejs测试mongoose,我对下面代码的行为有点困惑 在用户数据库中 var mongoose = require('mongoose'), Schema = mongoose.Schema, bcrypt = require('bcrypt'), SALT_WORK_FACTOR = 10; var UserSchema = new Schema({ username: {type: String, required: true, ind
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
username: {type: String, required: true, index: {unique: true}},
password: {type: String, required: true}
});
UserSchema.pre('save', function(next){
var user = this;
// only hash the password if it has been modified (or is newly created)
if (!user.isModified('password')) return next();
//generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt){
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, function(err, hash){
if(err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb){
bcrypt.compare(candidatePassword, this.password, function(err, isMatch){
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
在用户服务器中
var = User = require('./user-db.js');
function test_save(data){
var compare = new User({
username: 'compare3',
password: 'compare3'
});
compare.save(function(err){
if (err) throw err;
});
User.findOne({username: 'compare3'}, function(err, user){
if (err) throw err;
if (user){
console.log("you find compare 3");
}
});
以下是行为:
如果我想打印
“您找到了compare3”
我必须运行一次app.js,使用control-C关闭app.js,然后再次运行,user的第一次值为null
为什么呢?我想.pre不能像我想的那样工作,尽管我认为next()已经解决了这个问题
如果您有任何建议,我们将不胜感激,谢谢
您的代码不是以“线性”方式执行的,因此它不会在.save()
完成之前“等待”
这就是为什么所有函数都有“callback”方法。因此,当操作完成时,会调用其中的代码:
您需要将代码“放入”此文件中,如下所示:
compare.save(function(err){
if (err) throw err;
User.findOne({username: 'compare3'}, function(err, user){
if (err) throw err;
if (user){
console.log("you find compare 3");
}
});
});
然后,在文档保存后执行查找。在文档可能尚未保存之前
如果您打算使用Node.js,那么您需要在创建“非阻塞”程序时扩展对Node.js和相关样式的理解。尝试搜索这些术语,您会找到大量信息。谢谢您的回答