The correct way to return from mongo to datatable

I am using mongoose and returning documents from the collection to be displayed using datatables. However, I have some problems. Client code

var table = $('#dataTables-example').DataTable( { "bProcessing" : true, "bServerSide" : true, "ajax" : { "url" : "/mongo/get/datatable", "dataSrc": "" }, "columnDefs": [ { "data": null, "defaultContent": "<button id='removeProduct'>Remove</button>", "targets": -1 } ], "aoColumns" : [ { "mData" : "name" }, { "mData" : "price" }, { "mData" : "category" }, { "mData" : "description" }, { "mData" : "image" }, { "mData" : "promoted" }, { "mData" : null} ] }); 

This is then processed on the server side using the following

  db.once('open', function callback () { debug('Connection has successfully opened'); productSchema = mongoose.Schema({ name: String, price: String, category: String, description: String, image: String, promoted: Boolean }); Product = mongoose.model('Product', productSchema, 'products'); }); exports.getDataForDataTable = function (request, response) { Product.dataTable(request.query, function (err, data) { debug(data); response.send(data); }); }; 

If I use the code above, the datatable cannot display documents, claiming that no matching BUT records were found, it correctly displays the number of documents. Displays 1 to 2 of 2 entries. If I changed the server-side code to respond using data.data instead of data , the documents will be correctly filled in the BUT table, the number of records will no longer be found, instead, it will be shown that mapping 0 to 0 out of 0 records (filtered from general records NaN)

 exports.getDataForDataTable = function (request, response) { Product.dataTable(request.query, function (err, data) { debug(data); response.send(data.data); }); 

Valid data returned by mongo request,

 { draw: '1', recordsTotal: 2, recordsFiltered: 2, data: [ { _id: 5515274643e0bf403be58fd1, name: 'camera', price: '2500', category: 'electronics', description: 'lovely', image: 'some image', promoted: true }, { _id: 551541c2e710d65547c6db15, name: 'computer', price: '10000', category: 'electronics', description: 'nice', image: 'iamge', promoted: true } ] } 
+7
mongodb mongoose datatable
source share
2 answers

The third parameter in mongoose.model sets the name of the collection, which will be multiple and lower, automatically, so in this case there will be no effect.

Assuming your Product variable is declared early and global, try the following:

products = mongoose.model('products', productSchema); Product = require('mongoose').model('products');

0
source share

You tried to remove the dataSrc field in the DataTable configuration:

 "ajax" : { "url" : "/mongo/get/datatable", }, 
0
source share

All Articles