Git Product home page Git Product logo

datatables-query's Introduction

datatablesQuery

datatablesQuery is a module for making the integration between front-end tables using datatables and a REST API, node.js, express, MongoDB and Mongoose backed Servers, easier.

The main purpose is dealing with server side processing available in datatables, making it easy to integrate client and server.

Getting Started

Install the module.

npm install datatables-query

In your front-end, configure your DataTable to use serverSide processing and Ajax. The request type MUST be 'POST'.

// jQuery way
$('#example').DataTable( {
    serverSide: true,
    ajax: {
        url: '/path/to/api/endpoint',
        type: 'POST'
    }
} );
// Angular way - @see https://l-lin.github.io/angular-datatables/#/serverSideProcessing for full example

vm.dtOptions = DTOptionsBuilder.newOptions()
    .withOptions('serverSide', true)
    .withOptions('ajax', {
        url: '/path/to/api/endpoint',
        type: 'POST'
    })
    .// all other options

In your server, you MUST use body-parser with urlencoded extended

var app = express();

app.use(bodyParser.urlencoded({extended: true});

In the route handler, import the module and pass a reference to the mongoose model you wish to use as data source.

The DataTables params will get caught in the request body. It should be passed to the run method, which will return a promise.

app.post('/path/to/api/endpoint', function (req, res) {
    var Model = require('./path/to/model'),
        datatablesQuery = require('datatables-query'),
        params = req.body,
        query = datatablesQuery(Model);

    query.run(params).then(function (data) {
        res.json(data);
    }, function (err) {
        res.status(500).json(err);
    });
};

That's all folks. Your table should be working just fine.

Assumptions

As noted above, it is assumed that the server parses the request using extended urlencoded and that the data object is a Mongoose object.

Datatables with serverSide processing enabled makes POST requests with content-type application/x-www-form-urlencoded, and express' module body parser makes it easiear to work with this data, transforming it to JSON and parsing arrays and objects.

Using Without Datatables

One could use this module without datatables in the front-end making requests. For this to work, the POST body must be a configuration object equivalent to the one shown below:

// req.body should be equivalent to:
{
    "draw": "3",  // datatable stuff, but is mandatory nonetheless
    "start": "0",
    "length": "10",
    "search": {
        "value": ""
    },
    "columns": [
        {
            "data": "name", // field name in the MongoDB Schema
            "searchable": "true", // mandatory
            "orderable": "true" // mandatory
        },
        {
            // .. same structure as above for each field
        }
    ],
    "order": [
        {
            "column": "1", // index of the column used for sorting
            "dir": "asc" // direction of sorting ('asc' | 'desc')
        }
    ]
}

TODO

  • Add examples to this repo
  • Implement filter by column
  • Add tests to the 'run' method

Contributing

Feel free to fork and mess with this code. But, before opening PRs, be sure that you adhere to the Code Style and Conventions (run grunt lint) and add/correct as many tests as needed to ensure your code is working as expected.

License

The MIT License (MIT)

Fiddus Tecnologia

Copyright (c) 2015 Vinicius Teixeira [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

datatables-query's People

Contributors

ikenfin avatar vinicius0026 avatar

Stargazers

 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  avatar  avatar  avatar  avatar

datatables-query's Issues

Searching works only if all columns are Strings.

Error occurs when there is any non-string column across the table.
can you improve it so it search even through:

  • Numbers
  • Dates

Mongoose SchemaTypes:
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Decimal128
Map
Schema


  • Table Columns are
- username      = String
- age           = Number    // Couse of error
- gender        = String

  • Request POST
{
  "draw": "6",
  "columns": [
    {
      "data": "username",
      "name": "",
      "searchable": "true",
      "orderable": "true",
      "search": {
        "value": "",
        "regex": "false"
      }
    },
    {
      "data": "age",
      "name": "",
      "searchable": "true",
      "orderable": "true",
      "search": {
        "value": "",
        "regex": "false"
      }
    },
    {
      "data": "gender",
      "name": "",
      "searchable": "true",
      "orderable": "true",
      "search": {
        "value": "",
        "regex": "false"
      }
    }
  ],
  "order": [
    {
      "column": "0",
      "dir": "asc"
    }
  ],
  "start": "0",
  "length": "10",
  "search": {
    "value": "My Search Value",
    "regex": "false"
  }
}
  • Error response
{
  "error": {
    "stringValue": "\"/My Search Value/i\"",
    "valueType": "RegExp",
    "kind": "Number",
    "value": {},
    "path": "age",
    "reason": {
      "generatedMessage": true,
      "code": "ERR_ASSERTION",
      "actual": false,
      "expected": true,
      "operator": "=="
    },
    "name": "CastError",
    "message": "Cast to Number failed for value \"/My Search Value/i\" (type RegExp) at path \"age\" for model \"User\""
  }
}
  • Alert on browser
DataTables warning: table id=sortTable - Ajax error. 
For more information about this error,
please see http://datatables.net/tn/7

UnhandledPromiseRejectionWarning:

{
"draw": 1,
"length": 2,
"start":1,
"search": {
"value": "hrro"
},
"columns": [
{
"data": "title",
"searchable": "true",
"orderable": "true"
},
{
"data": "id",
"searchable": "true",
"orderable": "true"
}

],
"order": [
    {
        "column": "1",
        "dir": "asc" 
    }
]

}
but not getting filtering result .
getting all records

processing additional params in server-side datatables-query

I'm sending one additional parameter to the server .For eg: i have a collection named "bills" in which i'm storing the data of all my users with a specific "bill_id" and now i want to retrieve all bill details associated with one particular "bill_id".
So , i wanna know how can i get data based on key "bill_id", m already sending this additional param from front-end.

Search Fails For Number/Date Mongoose Schema

For example, when searching for a single letter ("t" in this case) the search is accurate when all number, and date fields are set to searchable:false. Otherwise this error is returned:

{ error: 
   { [CastError: Cast to number failed for value "/t/i" at path "campaignEstimate"]
     message: 'Cast to number failed for value "/t/i" at path "campaignEstimate"',
     name: 'CastError',
     kind: 'number',
     value: /t/i,
     path: 'campaignEstimate',
     reason: undefined } }

campaignEstimate is a simple number such as 1234

QUERY: How to populate other document?

Hi,
I am able to use this package and get the data on front-end side. But does it support to populate other document and display that data on front-end side?

Question: how does this related to MongoDB

Actually I used MongoDB very much during my project. every time, I write
python code to read mongo, URL to bind to that function and then on the UI, I use Datatable with ajax call to get the data.

I know mongo has some restful API supported by default. My question is will databases-query use the MongoDB restful API directly. If so I will not need to read from mongo, write URL anymore?

if so, how the username/password information is maintained.

Thanks for your time

Maintained?

Hi @vinicius0026,

this repo hasn't been updated in a while, so i was wondering, if you're still interested in maintaining this package?

I recently started working on a project with Mongoose/Datatables involved and came across this package. And while there are other packages out there, which i also gave a shot, this one seems to be the simplest one - and well, just works :)

The one thing i was missing, was the column search (which is also listed as a Todo in the README).

I've forked and updated some dependencies and added this functionality (as an initial draft). Are you generally interested in PRs and would merge them?

Otherwise i'd go on with my fork of it, because i'll probably need some more functionality in my project but am very willing to use this package :)

Best,
Joachim

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.