Created
September 11, 2017 14:42
-
-
Save thejohnnybot/20d30be5bffbc2b5f3feb03342106814 to your computer and use it in GitHub Desktop.
Example moongoose model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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