📅  最后修改于: 2023-12-03 15:00:36.213000             🧑  作者: Mango
EncryptedFields is a library that enables encrypting specific fields within a Mongoose model. This can be especially useful when dealing with sensitive data that should not be visible in plain text.
The library works by adding a layer of encryption to the fields specified within the model schema. When data is saved to the database, the specified fields are encrypted using a secret key that is stored securely outside of the database.
To use EncryptedFields, simply install the npm package:
npm i mongoose-encrypt
Then, require it in your code:
const encryptedFields = require('mongoose-encrypt');
Next, define a schema for your model, and specify which fields should be encrypted:
const userSchema = new mongoose.Schema({
name: String,
email: encryptedFields.encryptionProxy(String),
password: encryptedFields.encryptionProxy(String),
});
The encryptionProxy
method tells EncryptedFields to encrypt the field before saving it to the database.
Finally, when creating a new document for your model, simply assign values to the fields as usual:
const user = new User({
name: 'John Doe',
email: 'johndoe@example.com',
password: 'password123',
});
user.save();
EncryptedFields will automatically encrypt the specified fields before saving them to the database.
Overall, EncryptedFields is a powerful and easy-to-use library that can help ensure sensitive data remains secure in your Mongoose MongoDB environment.