UNPKG

hera-mongoose-to-json

Version:

A plugin for Mongoose to normalize JSON output

103 lines (73 loc) 1.94 kB
# hera-mongoose-to-json <p> <a href="https://www.npmjs.com/package/hera-mongoose-to-json" target="_blank"> <img alt="Version" src="https://img.shields.io/npm/v/hera-mongoose-to-json.svg"> </a> <a href="#" target="_blank"> <img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" /> </a> <a href="https://twitter.com/brokolililer" target="_blank"> <img alt="Twitter: brokolililer" src="https://img.shields.io/twitter/follow/brokolililer.svg?style=social" /> </a> </p> A plugin for Mongoose to normalize JSON output ## Installation You can install this package using `npm`. ```shell #npm npm install hera-mongoose-to-json --save ``` ## Usage Setup as a global plugin for all Mongoose schema's: ```js const mongoose = require('mongoose') const hmtj = require('hera-mongoose-to-json') //Global plugin mongoose.plugin(hmtj.toJSON) ``` Or for a specific (sub) schema: ```js const mongoose = require('mongoose') const hmtj = require('hera-mongoose-to-json') const MySchema = new Schema(/* ... */}) //Apply plugin MySchema.plugin(hmtj.toJSON) ``` This plugin will normalize JSON output for client side applications from: ```json { "_id": "400e8324a71d4410b9dc3980b5f8cdea", "__v": 2, "name": "Item A" } ``` To a cleaner: ```json { "id": "400e8324a71d4410b9dc3980b5f8cdea", "name": "Item A" } ``` You can also remove private paths from the JSON: ```js const mongoose = require('mongoose') const hmtj = require('hera-mongoose-to-json') const schema = new Schema({ email: {type: String}, password: {type: String, private: true}, }) schema.plugin(hmtj.toJSON) const User = mongoose.model('users', schema) const user = new User({email: 'test@test.com', password: 'test'}) console.log(user.toJSON()) ``` This will output: ```json { "id": "400e8324a71d4410b9dc3980b5f8cdea", "email": "test@test.com" } ``` ## License (MIT License) Copyright 2023, Burak Simsek