Code Monkey home page Code Monkey logo

mongoose-to-json's Introduction

@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

mongoose-to-json's People

Contributors

abhisekp avatar adamreisnz avatar taina0407 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mongoose-to-json's Issues

support for mongoose 5

Currently, mongoose 5 users will see the following warning when installing: npm WARN [email protected] requires a peer of mongoose@^4.5.4 but none is installed. You must install peer dependencies yourself.

I am on mongoose 5 myself and everything seem to work. Unfortunately there is no tests in this project so I can't say that for sure, but if you got time, I figured it'd be great to pump that supported version a bit.

Cheers

Not working with Common js Module

const mongoose_to_json_1 = require("@reis/mongoose-to-json");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/chertik/New Era/DrinkMaster-backend/node_modules/@reis/mongoose-to-json/index.js from /Users/chertik/New Era/DrinkMaster-backend/dist/src/schemas/category.schema.js not supported.
Instead change the require of index.js in /Users/chertik/New Era/DrinkMaster-backend/dist/src/schemas/category.schema.js to a dynamic import() which is available in all CommonJS modules.
at Object. (/Users/chertik/New Era/DrinkMaster-backend/dist/src/schemas/category.schema.js:14:28)

npm ERR! 404 Not Found

Hi,
When i try to install the library i'm receiving this error:

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/meanie-mongoose-to-json/-/meanie-mongoose-to-json-1.3.0.tgz - Not found
npm ERR! 404 
npm ERR! 404  'meanie-mongoose-to-json@https://registry.npmjs.org/meanie-mongoose-to-json/-/meanie-mongoose-to-json-1.3.0.tgz' is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

not working with mongoose 5.5.3

mongoose: 5.5.3
@meanie/mongoose-to-json: 2.3.0

Use case:
The findOneAndUpdate call returns:

{"__v": 0, "_id": "5c5ad0ca633de27c588a5bb1", "username": ...

FYI, works fine with mongoose: 5.5.2

dont work with multiple plugins

I use another plugin, but when I add your plugin, they dont work.

my code:

import mongoose from 'mongoose'
import privates from 'mongoose-private'
import mongooseToJson from 'meanie-mongoose-to-json'
import encode from '../encode/encode.helper.js'

const schema = new mongoose.Schema({
  email: {type: String, trim: true, required: true, unique: true},
  password: {type: String, required: true, set: encode.md5, private: true},
})

schema
  .plugin(privates)
  .plugin(mongooseToJson)

module.exports = mongoose.model('users', schema)
``

Doesn't work when setting up as a global plugin

Great plugin!
But all documents still have _id when using this example

const mongoose = require('mongoose');
const toJson = require('@meanie/mongoose-to-json');

mongoose.plugin(toJson);

model.aggregate, no work

Hi, I found this plugin at here and it was in model.find() works fine, but when I use model.aggregate(), the job fails. Is there any solution?

Using plugins

import { Schema, Types } from 'mongoose';
import * as toJSON from '@meanie/mongoose-to-json';

const EssaySchema = new Schema({
  title: String,
  content: String,
  published: { type: Date, default: Date.now },
  types: [Types.ObjectId],
  isDelete: { type: Boolean, default: false },
});

EssaySchema.plugin(toJSON);
export { EssaySchema };

When I use this.essayModel.aggregate().match({ _id }).lookup({ from: 'types', localField: 'types', foreignField: '_id', as: 'ts', })

expected results

[
  {
    "id": "5d56b4a70e593e119476a2b8",
    "types": [
      "5d56b4350e593e119476a2b4"
    ],
    "isDelete": false,
    "title": "js学习笔记",
    "content": "asdasdasdasdasdasda",
    "published": "2019-08-16T13:50:31.307Z",
    "ts": [
      {
        "id": "5d56b4350e593e119476a2b4",
        "description": "",
        "title": "js"
      }
    ]
  }
]

actual results

[
  {
    "_id": "5d56b4a70e593e119476a2b8",
    "types": [
      "5d56b4350e593e119476a2b4"
    ],
    "isDelete": false,
    "title": "js学习笔记",
    "content": "asdasdasdasdasdasda",
    "published": "2019-08-16T13:50:31.307Z",
    "__v": 0,
    "ts": [
      {
        "_id": "5d56b4350e593e119476a2b4",
        "description": "",
        "title": "js",
        "__v": 0
      }
    ]
  }
]

Problem of set other parameters

The plugin blocks the ability to set other parameters in the toJSON object (eq. virtuals)
Try add in index.js:17:

schema.options.toJSON = Object.assign(schema.options.toJSON || {}, {
...
}

toJSON is not considering the alias

I've a schema with alias but after toJSON, it is not giving the alias. Instead it gives the document property.
The alias is made so that aliases come as response instead of the original document property.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.