Skip to content

A simple plugin for Mongoose to normalize JSON output, for use with Meanie Express Seed projects

Notifications You must be signed in to change notification settings

adamreisnz/mongoose-to-json

Repository files navigation

@reis/mongoose-to-json

npm version github issues

A plugin for Mongoose to normalize JSON output

Installation

You can install this package using yarn or npm.

#yarn
yarn add @reis/mongoose-to-json

#npm
npm install @reis/mongoose-to-json --save

Usage

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

import mongoose from 'mongoose'
import {toJson} from '@reis/mongoose-to-json'

//Global plugin
mongoose.plugin(toJson)

Or for a specific (sub) schema:

import mongoose from 'mongoose'
import {toJson} from '@reis/mongoose-to-json'
const {Schema} = mongoose

//Define schema
const MySchema = new Schema(/* ... */})

//Apply plugin
MySchema.plugin(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:

import mongoose from 'mongoose'
import {toJson} from '@reis/mongoose-to-json'
const {Schema} = mongoose

const schema = new Schema({
  email: {type: String},
  password: {type: String, private: true},
})

schema.plugin(toJson)

const User = mongoose.model('users', schema)
const user = new User({email: '[email protected]', password: 'test'})

console.log(user.toJSON())

This will output:

{
  "id": "400e8324a71d4410b9dc3980b5f8cdea",
  "email": "[email protected]"
}

Issues & feature requests

Please report any bugs, issues, suggestions and feature requests in the mongoose-to-json issue tracker.

License

(MIT License)

Copyright 2016-2023, Adam Reis

About

A simple plugin for Mongoose to normalize JSON output, for use with Meanie Express Seed projects

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •