hera-mongoose-to-json

1.0.8 • Public • Published

hera-mongoose-to-json

Version License: MIT Twitter: brokolililer

A plugin for Mongoose to normalize JSON output

Installation

You can install this package using npm.

#npm
npm install hera-mongoose-to-json --save

Usage

Setup as a global plugin for all Mongoose schema's:

const mongoose = require('mongoose')
const hmtj = require('hera-mongoose-to-json')

//Global plugin
mongoose.plugin(hmtj.toJSON)

Or for a specific (sub) schema:

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:

{
  "_id": "400e8324a71d4410b9dc3980b5f8cdea",
  "__v": 2,
  "name": "Item A"
}

To a cleaner:

{
  "id": "400e8324a71d4410b9dc3980b5f8cdea",
  "name": "Item A"
}

You can also remove private paths from the JSON:

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:

{
  "id": "400e8324a71d4410b9dc3980b5f8cdea",
  "email": "test@test.com"
}

License

(MIT License)

Copyright 2023, Burak Simsek

Dependencies (0)

    Dev Dependencies (0)

      Package Sidebar

      Install

      npm i hera-mongoose-to-json

      Weekly Downloads

      2

      Version

      1.0.8

      License

      MIT

      Unpacked Size

      7.48 kB

      Total Files

      8

      Last publish

      Collaborators

      • burak-simsek