Mongoose Encryption Encrypts Both Fields. What Do I Do?
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");
        }
    });
});

So instead of getting 5 fields Im getting 4 fields with no username field

I tried different for different typos, different methods like excludefromencryption but it didnot work. I even tried dropping the collection starting anew.

1

1 Answer

If you are using the mongoose-encryption library ( ), that might be the problem. It's meant for encrypting entire documents as far as I'm aware.

Try using the mongoose-field-encryption library instead ( ), for encrypting specific fields.

Also: "Always store your keys and secrets outside of version control and separate from your database."

You probably already know this and has added the secret just for the example; but remember to not have the secret directly in the source code. Use something like an environment variable instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest