GithubHelp home page GithubHelp logo

jbutko / mongoose-find-and-filter Goto Github PK

View Code? Open in Web Editor NEW
2.0 3.0 1.0 5 KB

mongoose-find-and-filter plugin is a mongoose plugin which improves the find method with filtering and sorting features

License: Do What The F*ck You Want To Public License

JavaScript 100.00%
mongodb mongo mongoose mongoosejs mongoose-plugin nodejs

mongoose-find-and-filter's Introduction

Mongoose find and filter plugin

NPM

mongoose-find-and-filter plugin is a mongoose plugin which improves the find method with filtering and sorting features. You can also limit or skip results and populate refs.

Installation

npm install mongoose-find-and-filter --save

You can use this plugin with specific schema or globally for all schemas.
To use it with specific schema:

const mongooseFindAndFilter = require('mongoose-find-and-filter');

const userSchema = new Schema({...});

// attach mongoose-find-and-filter plugin to userSchema
userSchema.plugin(mongooseFindAndFilter);

If you want to use the plugin globally for all schemas:

const mongoose = require('mongoose');
const mongooseFindAndFilter = require('mongoose-find-and-filter');

mongoose.plugin(mongooseFindAndFilter);

After attaching mongoose-find-and-filter plugin you will have Model.findAndFilter(...) method on your model.

Usage

Mongoose find and filter plugin provides support for both promise style as well as callback style queries. Setup for your backend API server (eg. ExpressJS) might look something like this:

Promise example

const User = require('./user.model.js'); // model

/* this is example of User model instance
{
  "_id": "58e0dc934ee10d2f1c2cd0f4",
  "username": "johndoe",
  "contact": "58e68c594ee10d1870493af1", // ref to Contact model
  "updatedAt": "2017-04-05T05:31:00.522Z",
  "createdAt": "2017-02-16T08:32:17.959Z",
  "job": "58f0ab4e62697f2db41b2e69", // ref to Job model
  "age": 10,
  "email": "[email protected]",
  "surname": "doe",
  "firstName": "john",
  "password": "sdlkfjldksfjcdslkjdslkfjsdflkdsjkfsdfjsdfkf"
}
*/

let query = { age: { $gte: 1 } }; // default query
let queryParams = req.query; // query params from FE
let protectedKeys = ['email']; // protected keys == not searchable/filterable
let populate = [{
    path: 'contact',
    model: 'Contact',
    populate: {
      path: 'city',
      model: 'City'
    }
  },
  { path: 'job', model: 'Job' }
]; // populate refs

User
  .findAndFilter(query, queryParams, protectedKeys, populate)
  .then((users) => {
    // users will be documents with age>1 and further filtered by query sent as query params from FE
    res.status(200).json(users);
  })
  .catch((err) => {
    return next(err);
  });

Callback example

const User = require('./user.model.js'); // model

let query = { age: { $gte: 0 } }; // default query
let queryParams = req.query; // query params from FE
let protectedKeys = ['email']; // protected keys == not searchable/filterable
let populate = [{
    path: 'contact',
    model: 'Contact',
    populate: {
      path: 'city',
      model: 'City'
    }
  },
  { path: 'job', model: 'Job' }
];

User
  .findAndFilter(query, queryParams, protectedKeys, populate,
    (err, users) => {
      if (err) return next(err);
      // users will be documents with age>1 and further filtered by query sent as query params from FE
      res.status(200).json(users);
    });

Then if you want to query your endpoint send request in one of the following forms:

curl http://localhost:5005/api/v1/users // all users will be returned
curl http://localhost:5005/api/v1/users?username=johndoe // only docs with username=johndoe will be returned
curl http://localhost:5005/api/v1/users?username=johndoe&select=age username // only docs with username=johndoe will be returned and only age and username keys will be selected
curl http://localhost:5005/api/v1/users?username=johndoe&limit=5 // max 5 docs will be returned
curl http://localhost:5005/api/v1/users?username=johndoe&sort=_id // only docs with username=johndoe sorted by _id in ASC order will be returned
curl http://localhost:5005/api/v1/[email protected] // request will respond with 400 bad request as email is protected key
curl http://localhost:5005/api/v1/users?_id=58e0dc934ee10d2f1c2cd0f4 // only doc with _id=58e0dc934ee10d2f1c2cd0f4 will be returned

License

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004

Copyright (C) 2017 Jozef Butko [email protected]

Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  1. You just DO WHAT THE FUCK YOU WANT TO.

mongoose-find-and-filter's People

Contributors

hugocortes avatar jbutko avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

bilal-hanif

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.