有简单的计数猫鼬的方法吗?

时间:2018-07-20 03:55:12

标签: javascript node.js mongodb express mongoose

这是我的代码:

        Company.count({}, function(err, company) {
            Checkpoint.count({}, function(err, checkpoint) {
                Guard.count({}, function(err, guard) {
                    Device.count({}, function(err, device) {
                        res.json({
                            "success": true,
                            "count": {
                                "company": company,
                                "checkpoint": checkpoint,
                                "guard": guard,
                                "device": device
                            }
                        });
                    });
                });
            });
        });

这是最好的方法吗?还是有效率更高或更佳的东西?

2 个答案:

答案 0 :(得分:1)

  

使用承诺

通过这种方式可以使查询更快,更有效且更具可读性:

var countObj = {};
var countPromises = [
  Company.countDocuments({}).exec().then(count => countObj.company=count),
  Checkpoint.countDocuments({}).exec().then(count => countObj.checkpoint=count),
  Guard.countDocuments({}).exec().then(count => countObj.guard=count),
  Device.countDocuments({}).exec().then(count => countObj.device=count)
];

return Promise.all(countPromises)
  .then(() => res.json({
       "success": true,
       "count": countObj
  })

另外,请注意以下要点:

  1. 使用 countDocuments 代替 count count()方法具有 在最新版本的猫鼬中已弃用。
  2. 使用诺言,我建议的方法将使您的代码更快,因为它将同时在所有四个集合中进行查询,而不是像以前那样等待一个查询完成运行另一个查询>嵌套回调方式。
  3. 尝试使用Promises而不是回调,因为这会使您的代码更具可读性和可管理性。
  4. collection.query()方法始终返回查询对象,而不返回诺言。您必须调用.exec()方法将查询obj转换为实际的Promise,例如:collection.query()。exec()。

答案 1 :(得分:0)

    objects=[Company.Count({}),Checkpoint.Count({}),Guard.Count({}),Device.Count({})];
    response={};
    Promise.All(objects).then((values)=>{
    response=JSON.stringify({"success":true,"count":{"companies":values[0],"checkpoints":values[1],"guards":values[2],"devices"}}); 
   });

猫鼬处理计数的方式与您使用的方式一样好,但是,您的整体代码存在回调地狱的问题,因此可以简化使用 Promise.All()按照您想要的顺序来分配所有内容,然后从中创建一个JSON。

相关问题