node.js - Why does .pre in mongoose prevents accessing the record until next run? -
recently have been testing mongoose nodejs, , little confuse on behavior of following code
in user-db
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; // hash password if has been modified (or newly created) if (!user.ismodified('password')) return next(); //generate salt bcrypt.gensalt(salt_work_factor, function(err, salt){ if (err) return next(err); // hash password along our new salt bcrypt.hash(user.password, salt, function(err, hash){ if(err) return next(err); // override cleartext password hashed 1 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); in user-server
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"); } }); here behavior:
if want print
"you find compare3"
i have run app.js once, turn off app.js using control-c , run again, first time value user null
why that? assume .pre doesn't work wanted to, although thought next() has fixed issue?
any advice appreciated, thanks
it called "callback".
you code not executing in "linear" fashion does not "wait" until .save() completes.
this why functions have "callback"" methods. that code inside them called when operation completes:
you code needs "inside" this, in:
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"); } }); }); then find performed after document saved. before not saved yet.
if going working node.js need expand understanding of event loops , related styles in creating "non-blocking" programs. try searching on terms , should find plenty of information.
Comments
Post a Comment