angularjs - MEAN.js : Get number of users stored in MongoDB

标签 angularjs node.js mongodb express meanjs

我只是尝试使用 MEAN.js 向 MongoDB 提交查询。我想获取 Mongo 中存储的用户数量。 (所有已注册用户的数量)。

我正在处理一个由学生编写的 MEAN.js 网站,该网站非常困惑,由数千个 .js 文件组成。我发现两个文件可能相关:

app/controllers/users/users.authentication.server.controller.js

其中具有诸如 exports.signup = function(req, res) {...}exports.signin = function(req, res, next) {...} 的功能 在其中。

我添加:

exports.userCount = function(req, res) {
    // use mongoose to get the count of Users in the database
    User.count(function(err, count) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)

        res.json(count); // return return the count in JSON format
    });
}

问题是,假设该功能有效。和 bby 工作我的意思是返回 MongoDB 中“用户”记录的计数,目前尚不清楚如何调用它。理想情况下,我想将其称为前端的 50 个文件。

还有另一个文件,public/modules/users/controllers/authentication.client.controller.js

这个文件实际上是在前端迭代的,可以在firefox或chrome中调试。

它具有 $scope.signup = function() {...}$scope.signin = function() {...} 函数。

我想阻止显示登录页面,或显示备用消息,具体取决于 MongoDB 中的用户记录数。

当前的问题是我无法获取authentication.client.controller.js中的计数,因为它不知道“User”是什么。另一个问题是我不知道如何从前端或authentication.client.controller.js调用我在另一个文件中创建的函数exports.userCount

最佳答案

不要将服务器 Controller 与 Angular Controller 混淆。

在服务器 Controller 中,您应该有一个返回计数的函数,就像您所说的exports.userCount = function(req, res) {};。但是,如果您想调用该函数(API 样式),您必须在用户路由文件中定义一个路由:

app.route('/my-route-that-retrieves-user-count').get(user.userCount);`

一旦向路由 /my-route-that-retrieves-user-count 发出 GET 请求,您的 userCount 函数就会被调用。

在 AngularJS 端,您可以从 Authentication Controller 中发出类似 GET 请求(改编自 AngularJS 文档):

$http({
    method: 'GET',
    url: '/my-route-that-retrieves-user-count'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
    // response will be the count of users
    // you can assign that value to a scope and
    // act accordingly to its value
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

关于angularjs - MEAN.js : Get number of users stored in MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143804/

相关文章:

javascript - 收到错误 "c3"未定义 no-undef

AngularJS - 如何以编程方式创建一个新的、独立的范围?

angularjs - 如何创建一个 npm 脚本来运行多个命令来运行一些测试?

javascript - Codeigniter 在 foreach php 的 View html 中显示值

node.js - 捕获node.js中未捕获异常的源或行号

json - Express Angular - 从 POST 接收奇怪的 JSON

node.js - mongoose/mongodb 在聚合期间是否可以访问模式中的对象引用?

node.js - Stripe 无效请求错误: You can only create new accounts if you've signed up for Connect

javascript - 在MongoDB聚合函数中使用$project返回$group之后的某些数据

c++ - 如何使用 C++ 驱动程序处理 MongoDB 中 UserException 的数据类型错误