Skip to content

Instantly share code, notes, and snippets.

@thejohnnybot
Created September 11, 2017 14:42
Show Gist options
  • Select an option

  • Save thejohnnybot/20d30be5bffbc2b5f3feb03342106814 to your computer and use it in GitHub Desktop.

Select an option

Save thejohnnybot/20d30be5bffbc2b5f3feb03342106814 to your computer and use it in GitHub Desktop.
Example moongoose model
const mongoose = require('mongoose');
const { decrypt, encrypt } = require('../utils/crypto');
const { Schema } = mongoose;
const CheckoutSchema = mongoose.Schema({
userId: Schema.Types.ObjectId,
customerId: Schema.Types.ObjectId,
status: { type: String, enum: ['queued', 'sent', 'recovered'] },
provider: String,
metadata: Schema.Types.Mixed
});
CheckoutSchema.pre('save', function(next) {
if (typeof this.metadata === 'string') {
this.metadata = encrypt(this.metadata);
} else {
this.metadata = encrypt(JSON.stringify(this.metadata));
}
next();
});
CheckoutSchema.post('init', function(doc) {
if (typeof doc.metadata === 'string') {
doc.metadata = JSON.parse(decrypt(doc.metadata));
} else {
doc.metadata = decrypt(doc.metadata);
}
});
module.exports = mongoose.model('Checkout', CheckoutSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment