@anhkhoakz/mongoose-to-json
v1.2.3
Published
A Mongoose plugin to customize the toJSON output.
Readme
@anhkhoakz/mongoose-to-json
A Mongoose plugin to customize the toJSON output.
Installation
You can install this package using bun, yarn, or npm.
# bun
bun add @anhkhoakz/mongoose-to-json
# yarn
yarn add @anhkhoakz/mongoose-to-json
# npm
npm install @anhkhoakz/mongoose-to-json --saveUsage
Setup as a global plugin for specific Mongoose schemas:
import mongoose from 'mongoose'
import { toJSON } from '@anhkhoakz/mongoose-to-json'
const { Schema } = mongoose
// Define schema
const MySchema = new Schema({
name: String,
email: String
})
// Apply plugin
MySchema.plugin(toJSON)Default Transformations
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"
}By default, the plugin:
- Removes
__v(version field) - Converts
_idtoid - Removes private paths
Configuration Options
You can configure which transformations to apply by setting options:
import mongoose from 'mongoose'
import { toJSON } from '@anhkhoakz/mongoose-to-json'
const { Schema } = mongoose
const schema = new Schema({
email: { type: String },
password: { type: String, private: true },
name: String
})
// Disable specific transformations
schema.plugin(toJSON, {
toJSON: {
removeVersion: false, // Keep __v field
normalizeId: false, // Keep _id field
removePrivatePaths: false // Keep private paths
}
})Private Paths
The plugin automatically removes fields marked as private:
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: 'secret' })
console.log(user.toJSON())This will output:
{
"id": "400e8324a71d4410b9dc3980b5f8cdea",
"email": "[email protected]"
}Custom Transform Function
You can use the plugin with your own custom transform function:
schema.plugin(toJSON, {
toJSON: {
transform: (doc, ret) => {
// Your custom transformations
ret.customField = 'custom value'
return ret
}
}
})API Reference
toJSON(schema: Schema, options?: ToJSONOptions)
Applies the toJSON plugin to a Mongoose schema.
Options
removeVersion?: boolean- Remove__vfield (default:true)normalizeId?: boolean- Convert_idtoid(default:true)removePrivatePaths?: boolean- Remove private paths (default:true)transform?: TransformFunction- Custom transform function
License
Copyright (c) anhkhoakz
