如何将聚合查询与facet一起用于node.js服务器端数据表。
这是我的导出路由,用于将数据发送到node.js服务器端数据表
代码可以正常工作,但是实际代码不利于生产,因为查询数据库3次只是为了生成一个表,一次查询总数,一次查询过滤后的数据,一次查询实际数据。 更好的方法是使用带有$ facet的聚合管道只查询一次数据库,然后分离结果,但是我不知道,请问是否有人使用过$ facet查询并得出结果解决方案。张贴在这里供大家理解。
exports.postDashboardCDR = (req, res, next) => {
var searchStr = req.body.search.value;
if (req.body.search.value) {
var regex = new RegExp(req.body.search.value, "i")
searchStr = { $or: [{ 'src': regex }, { 'start': regex }, { 'answer': regex }, { 'end': regex }, { 'sequence': regex }] };
} else {
searchStr = {};
}
var recordsTotal = 0;
var recordsFiltered = 0;
CdrModel.estimatedDocumentCount({}, function(err, c) {
recordsTotal = c;
console.log(c);
CdrModel.countDocuments(searchStr, function(err, c) {
recordsFiltered = c;
console.log(c);
console.log(req.body.start);
console.log(req.body.length);
CdrModel.find(searchStr, '_id src start answer end sequence', { 'skip': Number(req.body.start), 'limit': Number(req.body.length) }, function(err, results) {
if (err) {
console.log('error while getting results' + err);
return;
//return next(new Error('No order found. ' + err));
}
var data = JSON.stringify({
"draw": req.body.draw,
"recordsFiltered": recordsFiltered,
"recordsTotal": recordsTotal,
"data": results
});
res.send(data);
//console.log(data);
});
});
});
};
**Mongoose cdr.js**
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cdrDTOptions = {
timestamps: true,
toJSON: {
virtuals: true
},
toObject: {
virtuals: true
}
};
const cdrDTSchema = new Schema({
_id: String,
src: String,
start: String,
answer: String,
end: String,
sequence: String
}, cdrDTOptions);
module.exports = mongoose.model('Cdrs', cdrDTSchema);