Skip to content
the poor coder

how to use mongoose-encryption

Poor Man
Published
Reading time
3 min read
On this page

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.

JavaScript
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.

JavaScript
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.

JavaScript
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.

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

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

const user = new User({
  email: "test@example.com",
  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.

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

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

User.findOne({ email: "test@example.com" }, (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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC