【问题标题】:Calling to an aggregation function using GET request使用 GET 请求调用聚合函数
【发布时间】:2019-09-17 23:25:26
【问题描述】:

我正在尝试从 A GET 请求中调用我的聚合函数,但响应为 EMPTY。

有人可以帮我解决这个问题吗?这是我的代码:

聚合函数:

function t1(callback) {
  userScheme.aggregate([
 // Unwind the array
{ "$unwind": "$result"},

// Group on the "_id" and "name" and $sum "value"
{ "$group": {
   "_id": { 
       //"_id": "$_id",
       "game": "$result.game"
   }, 
   "time": { "$avg": "$result.time" } 
}},

// Put things into an array for "nice" processing
{ "$group": {
   "_id": "$_id",
   "values": { "$push": { 
       "game": "$_id.game",
       "time": "$time"
   }}
}}
 ] , callback) 
}

我的GET 请求:

userRoutes.route('/getavg').get(function(req, res) {
    t1(function(err, user) {
        if (err)
                res.status(500).send("Internal error occurred.");
        else
                res.json(user);
    })
});

我做错了什么?

【问题讨论】:

  • 1) 从聚合管道中删除所有阶段,看看你得到了什么。 2) 你的生活方式很老套(callbacks)。尝试使用 async await 使用新的东西
  • 当我在聚合函数打印响应时,我得到了数据,所以我认为问题出在我的 GET 函数上
  • 我看不出上面的代码有什么问题。您可能检查了错误的位置或错误的文件。

标签: node.js mongodb mongoose aggregate


【解决方案1】:

代码看起来不错。

我建议您尝试简化您的代码。 首先将 get 函数替换为

userRoutes.route('/getavg').get(function(req, res) {
  console.error("Testing");
  res.json({test: "works});
});

然后查看是否收到响应或是否看到控制台错误。 如果还是不行,那就是路由问题

【讨论】:

  • 您好 Nim,非常感谢您的回复!这正是路由问题。
猜你喜欢
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2018-01-22
相关资源
最近更新 更多