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 } ] }