【发布时间】:2015-07-01 10:45:36
【问题描述】:
我正在使用 Nodejs Expressjs MongoDB 和 Mongoose 为我从事的小型服务应用程序创建 rest API。
我完成了所有路线,应用了 .find() 等简单的函数 .findOneAndUpdate() 等 喜欢这个:
router.get('/testTable', function(req, res, next) {
TestModel.find(function (err, testTableEntries) {
if (err) return next(err);
res.send(testTableEntries);
});
});
很简单。但是,如果我想合并更多的函数,那么只需要一个 mongo 函数 .find()
如果我想怎么办:
.find().pretty()
或者,如果要汇总,请进行一些计数:
.find().count()
.find({"fieldName": "How many have this value?"}).count()
.find({"fieldName": "How many have this value?"}).count().pretty()
我尝试了类似的方法:
router.get('/testTable', function(req, res, next) {
TestModel.find(function (err, testTableEntries) {
if (err) return next(err);
res.send(testTableEntries);
}).count();
});
或者,也许您可以建议使用 promise 的无回调解决方案(如 Bluebird),我的第一个想法是:
router.get('/testTable', function(req, res, next) {
TestModel.find(function (err, next) {
if (err) return next(err);
}).then(function (req, res, next) {
res.send(testTableEntries);
}).catch(function (err, next) {
if (err) return next(err);
});
});
也许有一些 Mongoose 内置函数可以解决这个问题,我将不胜感激,但知道如何在 Mongoose 模型上一个接一个地调用函数也会很有用。
提前感谢您的任何建议和想法!
【问题讨论】:
标签: node.js mongodb function mongoose chaining