Skip to content

Instantly share code, notes, and snippets.

@peteradeojo
Created April 25, 2024 21:04
Show Gist options
  • Select an option

  • Save peteradeojo/2829574febb0e2af05d37421034dfc60 to your computer and use it in GitHub Desktop.

Select an option

Save peteradeojo/2829574febb0e2af05d37421034dfc60 to your computer and use it in GitHub Desktop.
Create API-safe responses with mongoose toJSON()
// 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);
// 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