Mongoose Encryption意外加密username字段,仅加密password如何解决?
解决Mongoose Encryption插件意外加密所有字段的问题
问题描述
使用Mongoose Encryption插件时,已在adminsSchema中配置仅加密password字段,但实际数据库中未显示username字段,仅存在4个系统字段(如_id、__v、encrypted、iv),疑似所有字段都被加密。已尝试检查拼写、使用excludeFromEncryption方法、删除重建集合等操作,问题未解决。
相关代码:
Schema定义
const adminsSchema = new mongoose.Schema({ username: String, password: String, }); const secret = "Thinkyoucancrackthisone"; adminsSchema.plugin(encrypt, { secret: secret, encryptedFields: ["password"] }); const Admin = new mongoose.model("Admin", adminsSchema);
注册接口
app.post("/register", function (req, res) { const user = new Admin({ username: req.body.user, password: req.body.pass }); user.save(function (err) { if (err) { res.send(err); } else { res.send("Admin creds added successfully"); } }); });
解决方案
- 显式组合加密与排除配置:同时指定
encryptedFields和excludeFromEncryption,确保插件明确识别需要保留的字段:adminsSchema.plugin(encrypt, { secret: secret, encryptedFields: ["password"], excludeFromEncryption: ["username"] }); - 验证传入数据有效性:在保存前打印
user对象,确认username确实被正确赋值:app.post("/register", function (req, res) { const user = new Admin({ username: req.body.user, password: req.body.pass }); console.log("待保存用户数据:", user); // 检查username是否存在 user.save(function (err) { if (err) { res.send(err); } else { res.send("Admin creds added successfully"); } }); }); - 升级/降级插件版本:部分旧版本的
mongoose-encryption可能存在配置逻辑bug,尝试升级到最新稳定版,或回退到已知兼容的版本:npm install mongoose-encryption@latest - 确保Schema字段定义正确:给
username字段添加required: true约束,避免因字段为空被插件特殊处理:const adminsSchema = new mongoose.Schema({ username: { type: String, required: true }, password: { type: String, required: true }, }); - 检查Mongoose版本兼容性:确保
mongoose与mongoose-encryption版本匹配,避免因框架版本差异导致的配置失效。
内容的提问来源于stack exchange,提问作者Chirag Redij
相关产品推荐
相关产品推荐

