Created
April 25, 2024 21:04
-
-
Save peteradeojo/2829574febb0e2af05d37421034dfc60 to your computer and use it in GitHub Desktop.
Create API-safe responses with mongoose toJSON()
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
| // model.ts | |
| import mongoose, { Schema } from 'mongoose'; | |
| const schema = new Schema({ | |
| //...schema definition | |
| }); | |
| schema.methods.toJSON = function() { | |
| // ... compute some data to go along with your response | |
| return { | |
| ...this._doc, | |
| // set any secret fields to undefined. | |
| // add any computed data to response body. | |
| }; | |
| } | |
| export const Model = mongoose.model('model', schema); | |
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
| // router.ts | |
| import { Router } from 'express'; | |
| import { Model } from './model'; | |
| const router = Router(); | |
| router.get('/', async (req, res) => { | |
| const data = await Model.find(req.query); //- my cheat code for applying filters, limit, search lol don't judge me | |
| return res.json(data); // returns a sanitized/computed/secure response after coverting to JSON. | |
| }); | |
| export default router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment