how to use mongoose-encryption

Using Mongoose-Encryption

If you want to protect your data in MongoDB from prying eyes, you can use Mongoose-Encryption. This Node.js module is designed to encrypt your sensitive data in the database with a user-defined password. Let's see how to use it.

Step 1: Install Mongoose-Encryption

Before you can start using Mongoose-Encryption, you need to install it in your Node.js environment.

npm install mongoose-encryption

Step 2: Create a Schema for Your Mongoose Model

You will need to create a Mongoose schema for the model that will have encrypted fields. In this example, let's say we have a User model with an email and password field that we want to encrypt.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  email: String,
  password: String
});

Step 3: Add the Encryption Plugin to Your Schema

Now that we have our schema, we need to add the encryption plugin to it. This plugin will automatically encrypt and decrypt the specified fields when they are saved and retrieved from the database.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const encrypt = require('mongoose-encryption');

const userSchema = new Schema({
  email: String,
  password: String
});

// add encryption plugin to schema
const secret = "mysecret";
userSchema.plugin(encrypt, { secret: secret, encryptedFields: ['password'] });

In this example, we are using the 'password' field as the field to encrypt. You can add multiple fields to the encryptedFields array if you need to encrypt more than one field.

Step 4: Create and Save a New Document

Now that we have our schema with the encryption plugin, we can create a new document and save it to the database.

const mongoose = require('mongoose');
const User = require('./models/user');

mongoose.connect('mongodb://localhost/myapp', { useNewUrlParser: true, useUnifiedTopology: true });

const user = new User({
  email: "[email protected]",
  password: "password123"
});

user.save((err) => {
  if (err) {
    console.log(err);
  } else {
    console.log("User saved successfully!");
  }
});

The 'password' field in this document will be automatically encrypted before it is saved to the database.

Step 5: Retrieve and Decrypt a Document

To retrieve and decrypt a document with encrypted fields, you simply need to retrieve it from the database as you normally would.

const mongoose = require('mongoose');
const User = require('./models/user');

mongoose.connect('mongodb://localhost/myapp', { useNewUrlParser: true, useUnifiedTopology: true });

User.findOne({ email: "[email protected]" }, (err, user) => {
  if (err) {
    console.log(err);
  } else {
    console.log(user.password); // this will be the decrypted password
  }
});

The 'password' field in this document will be automatically decrypted before it is returned from the database.

Multiple Ways to Use Mongoose-Encryption

There are a few different ways to use Mongoose-Encryption depending on your needs. Here are a few examples:

  • You can encrypt all fields in a schema by not specifying any encryptedFields.
  • You can encrypt multiple fields in a schema by adding them to the encryptedFields array.
  • You can use a different password for each encrypted field by passing an object to the encryptedFields array with the field name as the key and the password as the value.

Overall, Mongoose-Encryption is a great way to add an extra layer of security to your MongoDB database without too much hassle.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe