我定义了一个User
模型,如下所示:
const mongoose = require('mongoose');
const hash = require('../util/hash');
const userSchema = new mongoose.Schema({
name: {
first: String,
last: String,
},
username: { type: String, lowercase: true, trim: true, unique: true },
passwordHash: String,
});
userSchema.virtual('password').set(function (password) {
this.passwordHash = hash(password);
});
userSchema.method('verify', function (password) {
return this.passwordHash === hash(password);
});
module.exports = mongoose.model('User', userSchema);
现在,我不想使用上面的verify
方法,而是希望发出如下查询:
const user = await User.findOne({ username, password });
也就是说,将密码本身而不是哈希值指定为过滤器,然后让Mongoose以某种方式在幕后发挥作用,并将其转换为{ username, passwordHash: hash(password) }
。
完成此任务的最佳方法是什么?