Phi*_*ien 7 datatable mongoose mongodb
我正在使用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}
]
});
Run Code Online (Sandbox Code Playgroud)
然后使用以下方法在服务器端处理
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);
});
};
Run Code Online (Sandbox Code Playgroud)
如果我使用上面的代码,数据表无法显示文档,声称没有找到匹配的记录 但是它确实显示了显示1到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);
});
Run Code Online (Sandbox Code Playgroud)
data查询mongo时返回的实际值是
{ 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 } ] }
Run Code Online (Sandbox Code Playgroud)
第三个参数mongoose.model设置集合名称,该名称自动为复数和小写,因此在这种情况下不起作用。
假设您的Product变量已提前声明为全局变量,请尝试以下操作:
products = mongoose.model('products', productSchema);
Product = require('mongoose').model('products');
| 归档时间: |
|
| 查看次数: |
1614 次 |
| 最近记录: |