Node.js 对模型对象应用多个函数的Mongoose模型
我正在使用Nodejs-Expressjs-MongoDB和Mongoose为我正在使用的一个小型服务应用程序创建restapi 我使用了一个简单的函数,比如.find() .findOneAndUpdate()等。 像这个:Node.js 对模型对象应用多个函数的Mongoose模型,node.js,mongodb,function,mongoose,chaining,Node.js,Mongodb,Function,Mongoose,Chaining,我正在使用Nodejs-Expressjs-MongoDB和Mongoose为我正在使用的一个小型服务应用程序创建restapi 我使用了一个简单的函数,比如.find() .findOneAndUpdate()等。 像这个: router.get('/testTable', function(req, res, next) { TestModel.find(function (err, testTableEntries) { if (err) return ne
router.get('/testTable', function(req, res, next) {
TestModel.find(function (err, testTableEntries) {
if (err) return next(err);
res.send(testTableEntries);
});
});
很简单。但是,如果我想合并更多的函数,而不是一个mongo函数呢
如果我想:
.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();
});
或者你可以建议无呼叫解决方案(如蓝鸟),我的第一个想法是:
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模型上一个接一个地调用链中的函数也会很有用
我提前感谢您的建议和想法 你可以直接打电话:
Test.count({"fieldName": "How many have this value?"},function(err,count) {
// count is the counted results
});
当然,从mongoose中的`.find()返回的对象是一个数组,因此:
Test.find({"fieldName": "How many have this value?"},function(err,results) {
var count = results.length;
})
或者对于“链接”,您可以使用“查询”来执行此操作
如果需要所有可能的“fieldName”值的“计数”,请使用.aggregate()
:
通常,您需要开始考虑异步编程中回调的“内部工作”,而不是将方法调用的结果“返回”到“外部”变量。谢谢,这非常好!最后的代码是router.get('/testTable/:someFiledId',function(req,res){Model.count({“someFieldId”:req.params.someFieldId}).exec(function(err,count){var jsoncount={“count”:count};if(err)返回err;res.send(jsoncount);});
Test.find({"fieldName": "How many have this value?"})
.count().exec(function(err,results) {
})
Test.aggregate([
{ "$group": {
"_id": "fieldName",
"count": { "$sum": 1 }
}},
],function(err,results) {
// each result has a count
});