1.2.0 • Published 6 years ago
mongoose-querier v1.2.0
mongoose-querier
Mongoose plugin which helps in querying Schema and supports pagination, filters, selection, searching, sorting.
Table of Contents
Installation
npm install mongoose-querier -SSetup
Add mongoose-paginate-v2 plugin and index the schema.
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(mongoosePaginate);
bookSchema.index({ '$**': 'text' });
module.exports = mongoose.model('Book', bookSchema);Usage
// import plugin
const Querier = require('mongoose-querier');
// import Book Schema
const Book = require('./Book');
const method = async () => {
const data = {
id: 'list',
options: {
select: ['_id', 'title'],
},
};
const populate = [{ path: 'author', model: 'Author' }];
const res = await Querier(Book, data, populate);
};API
await Querier([schema], [data], [populate], [defaultQuery]);Parameters
[schema]{Object} Mongoose Schema Model (required)[data]{Object} (required)id{String} Can be valid Mongoose ObjectId orlist(required)filters{Object[]} Data for performing filters (optional)type{String} Can bematchormultiordatekey{String} Schema field on which the filter operation will be performeddata{Any} Data to perform the filter
options{Object} Options for plugin (optional)select{String[]} Keys which has to be present in the response (optional, by default sends all key)search{String} Schema wide search (optional, by default value is null)
populate{Object[]} Mongoose Populate wihch takes in array of objects (optional)defaultQuery{Object} Default queries can also be passed here (optional, by default it's empty)
Examples of data.filters field
[
{ type: 'match', key: 'author', data: 'ObjectId' },
{ type: 'multi', key: 'genre', data: ['Fantasy', 'Horror'] },
{ type: 'date', key: 'publishDate', data: { from: 'date', to: 'date' } },
]