@cylution/mongoose-plugin-object-id-to-string
v1.0.4
Published
Simple mongoose plugin that auto convert ObjectId to string
Downloads
215
Maintainers
Readme
@cylution/mongoose-plugin-object-id-to-string
Simple mongoose plugin that auto convert ObjectId to string
Getting started
Install
npm i @cylution/mongoose-plugin-object-id-to-string
or
yarn add @cylution/mongoose-plugin-object-id-to-string
Usage
This plugin will add
toObject: { getters: true }
to mongoose schema optionsIf you don't want to modify a schema, just add
toObject: {}
to schema options
const demoSchema = new Schema({
name: String
}, {
toObject: {}, // will ignore toObject in global usecase
toJSON: {}, // will ignore toJSON in global usecase
})
Typescript
import { mongoosePluginObjectIdToString } from '@cylution/mongoose-plugin-object-id-to-string'
import { plugin, Schema } from 'mongoose'
Javascript
const { mongoosePluginObjectIdToString } = require('@cylution/mongoose-plugin-object-id-to-string')
const { plugin } = require('mongoose')
// don't forget this
const pluginObjectIdToString = mongoosePluginObjectIdToString(
v => v == null ? null : v.toString(), // convert function, can be simple: v => v.toString() if you ensure v is never null
[
'toObject',
'toJSON',
] // options
)
// global
plugin(pluginObjectIdToString)
// or schema
const userSchema = new Schema({
//
})
userSchema.plugin(pluginObjectIdToString)
License
This project is licensed under the MIT License.