mongodb-collection-query-with-mongose

2.0.4 • Public • Published

Full Article click here

no longer maintained click here for the updated version

This module is used to query a single  mongodb collection written with mongoose dynamically with simple query parameters using mongodb query types 'AND' and 'OR' with  MongoDB filter options eg '$gt' as 'gt', '$gte' as 'gte', '$lt' as 'lt', '$lte' as 'lte', '$eq' as 'eq' and 'cn' for case insensitive query for contains replacing MongoDB regex expression eg '/.*Will Abule.*/i'. 

The client(s) consuming your API just has to follow simple roles or better a query structure and it dynamically query and return an object as the result containing four fields rows, records, page, and total.

rows representing the queried data, records representing the total records found based on the filter, page representing the current page, and total representing the number of pages.

How To Use


Form your Node App


run npm i -s mongodb-collection-query-with-mongose


Post model file

const mongoose = require("mongoose");
const postScheama = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
  },
  imageUrl: {
    type: String,
    required: true,
    unique: true
  },
  userId: {
    type: String
  },
});
const Post = mongoose.model("Post", postScheama);
module.exports.postScheama = postScheama;
module.exports.Post = Post;


post route file

const getResReq = require("mongodb-collection-query-with-mongose");
const { Post } = require("./post-model");
const express = require("express"); 
const router = express.Router();

router.get("/post", [authGaurd], async (req, res) => {     const setect = "_id title userId description imageUrl"    const data = await Promise.all([ getResReq(req, res, Post, select) ]);     if (data.type === "error") return res.status(500).send({ message : internal server error, error: data})    res.send(data[0]) });


From Client


don't install the package for reading only if your backend developer uses this library


filter (boolean): If you want the collection to filtered or not, if true the search filter is required

row (number): The page size that is the number of bashes you want records to be sent

 page (number): The page  from the filtered collection

sortName (string): What field in the document to want the result to be sorted with eg a collection of users can be sorted by fristName  

sort (string): the sort order either ascending as 'asc' or descending as 'desc'

searchFilter (string): a stringified object with the following fields: searchOption, and rules

searchOption: either 'AND' or 'OR' in uppercase. AND will return data if all search rules evaluate to true, 'OR' will return data if all one or multiple of the rules are set to true.

rules: An array of objects, each object must have the following fields

field: The document field

option: how you want it to be quired. This is to be set to either the following 

cn (contains)

eq (equal)

gt (greater than)

gte (greater than or equal)

lt (less than)

lte (less than or equal)


data: The value of the field

type: The data type of the data. it must be set to either of the following

number

float

string

date

boolean


query filter rules

cn (contains): can only be used for string values

eq (equal): can be used for the following string, date, boolean float, number

gt (greater than): can be used for the following string, date, boolean float, number

gte (greater than or equal): can be used for the following string, date, boolean float, number

lt (less than): can be used for the following string, date, boolean float, number

lte (less than or equal): can be used for the following string, date, boolean float, number


Example So if you want to query a collection of users that the name or the email  contains will

const searchFilters = {
    searchOption:"OR",
    rules:[{
        field:"name",
        option:"cn",
        type:"string",
        data:"will"
    },{
        field:"email",
        option:"cn",
        type:"string",
        data:"will"
    }]
}

if you want to query a collection of post that the title or the description contains will and userId is 1234 

const searchFilters = {
    searchOption:"AND",
    rules:[{
        field:"title",
        option:"cn",
        type:"string",
        data:"will"
    },{
        field:"description",
        option:"cn",
        type:"string",
        data:"will"
    },{
        field:"userId",
        option:"eq",
        type:"string",
        data:"will"
    }]
}

if you want to sort the result in a descending by name then I will do something like this

const query = {
    sort          : 'desc',
    sortName      : 'title',
}

if you want to the result to be filtered I will do something like this

const query = {
    filter        : true,
    searchFilters : JSON.stringify(searchFilters)
}


if you want the result to brought by 10 batches starting from page 1 I will do something like this

const query = {
    page : 1,
    rows : 10
}


so the end result will look like this

const searchFilters = {
    searchOption:"AND",
    rules:[{
        field:"title",
        option:"cn",
        type:"string",
        data:"will"
    },{
        field:"description",
        option:"cn",
        type:"string",
        data:"will"
    },{
        field:"userId",
        option:"eq",
        type:"string",
        data:"will"
    }]
}
const query = {
    filter        : true,
    page          : 1,
    rows          : 10
    sort          : 'desc',
    sortName      : 'title',
    searchFilters : JSON.stringify(searchFilters)
}


Result for the API will look like this

Result : {
    rows: array,
    records: number,
    page: number,
    total: number
}


rows (array): The data found in the collections eg post collection

records (number): The total records found in the collections eg post collection

page (number): The page you specified records should start from in the collections eg post collection

total (number): The number of pages in the collections eg post collection


Package Sidebar

Install

npm i mongodb-collection-query-with-mongose

Weekly Downloads

21

Version

2.0.4

License

ISC

Unpacked Size

22 kB

Total Files

9

Last publish

Collaborators

  • willxd42