You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:01:14