绕过mongoose吸气

我试图在发送之前使用mongoose获取所有用户密码。 它完美的作品。 但是,在方法“comparePassword”,我需要密码串比较sothen我可以进行身份​​validation。

有没有在mongoose某些条件下绕过吸气的方法? 提前致谢!

代码示例:

function castpassword (pw) { return 'keyboard cat'; } var AccountSchema = new Schema({ password: { type: String, get: castpassword } }); AccountSchema.methods.comparePassword = function (candidatePassword, cb) { // random hash vs keyborad cat === not authenticated crypt.compare(candidatePassword, this.password, function (err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; .... Account.findById( someId, function (err, found) { console.log(found.password); // 'keyboard cat' }); 

mongoose中使用this.toObject()将绕过mongoose中的所有getter和setter设置,因为它将其更改为普通的JSON数据

 AccountSchema.methods.comparePassword = function (candidatePassword, cb) { // keyboard cat vs keyboard cat === authenticated crypt.compare(candidatePassword, this.toObject().password, function (err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; 

你可以使用mongoose'瘦'跳过所有的mongoose的魔法,只是拉出一个JSON对象。

 Account .findById(someId) .lean() .exec(function (err, found) { console.log(found.password); // actual password // you can not use mongoose functions here ex: // found.save() will fail }) 

另一个select是将模式中的密码设置为“select:false”。

 var AccountSchema = new Schema({ password: { type: String, select: false } }); 

通过这种方式,只要你没有特别指出,那么你在任何时候把文件拉出来的时候,密码字段根本就不存在。

 Account .findById(someId, function (err, found) { console.log(found.password); // undefinded }) Account .findById(someId) .select('password') // explicitly asking for password .exec(function (err, found) { console.log(found.password); // actual password })