正确的方式从mongo返回到datatable

时间:2015-03-27 12:09:34

标签: mongodb datatable mongoose

我使用mongoose并从集合中返回文档以使用数据表显示。我有一些问题。客户端代码是

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

然后使用以下

在服务器端处理
 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);
   });
};

如果我使用上面的代码,数据表无法显示文档,声称​​找不到匹配的记录 但是它确实显示了文档的数量显示1至2个条目中的2个。如果我将服务器端代码更改为使用data.data而不是data进行回复,则表格中正确填充文档但是不再找到记录数,而是说显示0个条目中的0到0(从NaN总条目中过滤掉)

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

查询mongo时返回的实际data

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

2 个答案:

答案 0 :(得分:0)

mongoose.model中的第三个参数设置了自动复数和小写的集合名称,因此在这种情况下无效。

假设您的Product变量已在早期和全局声明,请尝试以下操作:

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

答案 1 :(得分:0)

您是否尝试删除DataTable配置中的dataSrc字段:

"ajax" : {
    "url" : "/mongo/get/datatable",
},