📅  最后修改于: 2023-12-03 15:17:42.928000             🧑  作者: Mango
Mongoose-encryption is a Node.js module that provides encryption and decryption functionality for Mongoose models. It allows developers to encrypt specified fields within a model before saving it to the database, and decrypt those fields when retrieving the model from the database.
You can install this module using NPM:
npm install mongoose-encryption
To use mongoose-encryption, you first need to require it and define a schema for your Mongoose model. You can then apply the encryption plugin to the schema and specify the fields that you want to encrypt.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const encryption = require('mongoose-encryption');
const userSchema = new Schema({
username: String,
password: String,
email: String
});
const secret = 'topsecretkey';
userSchema.plugin(encryption, { encryptedFields: ['password'], secret: secret });
When you save a model instance of this schema, the password field will be automatically encrypted before being saved to the database.
const User = mongoose.model('User', userSchema);
const user = new User({ username: 'test', password: 'password', email: 'test@example.com' });
user.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('User saved successfully');
}
});
When you retrieve the encrypted data from the database, the specified fields will be automatically decrypted.
User.findOne({ username: 'test' }, function (err, user) {
if (err) {
console.log(err);
} else {
console.log(user.password); // 'password'
}
});
The encryption
plugin accepts a configuration object with the following options:
encryptedFields
- an array of strings that represent the names of the fields to be encryptedsecret
- a string that represents the secret key used for encryption and decryptionexcludeFromEncryption
- an array of strings that represent the fields to be excluded from encryptiondecryptPostSave
- a boolean that determines whether to decrypt the encrypted fields after saving the documentdecryptPreSave
- a boolean that determines whether to decrypt the encrypted fields before saving the documentMongoose-encryption is a useful tool for Node.js developers who want to encrypt sensitive data in their Mongoose models. It provides an easy-to-use plugin that automatically encrypts and decrypts specified fields, making it simple to ensure that data is secure both in transit and at rest.