将MongoDB聚合结果传递回路由

时间:2016-03-25 18:06:25

标签: node.js mongodb mongoose aggregation-framework

我读了几篇聚合文章,但我还是做空了。

聚合是测试元素是否在文档中。如果它返回的结果不是空数组,那么我知道要“检查”该框。

这是我到目前为止的代码,以及对我尝试过的一些评论。

router.get("/challenge/:challengeId", requireLogin, function(req, res) {

    var challengeId = req.params.challengeId;

    var isSolved = function(challengeId){
      console.log("in the aggregation: ", challengeId); // returns challengeId
      User.aggregate([
    //var isSolved = User.aggregate([
        { $match: {"solvedChallenges": { "challenge": challengeId } } },
        { $project: {
          userName: 1 }
        }
      ],
      function(err, results){
        console.log("this is the result: ", results); // logs a result if the there is one, and [] if there is no result.
        return results; // Trying to pass the results back to the /challenge/:challengeID route.
      });
    }

    //line below should return something like: []
    // or [ { _id: 56f5544bc171b1b8663bb15f, userName: 'John' } ]
    console.log("is solved is: ", isSolved(challengeId)); 
...



});

我正在尝试获取结果,将它们设置为变量,并查看该变量是否真实。如果真的如此,那么我会检查方框,如果是假的,那么保持不加以控制。

另外,如果我做的事情非常糟糕,我很乐意收到反馈。

1 个答案:

答案 0 :(得分:2)

在User.aggregate()的回调中返回一个值,不会将其返回给调用者。所以isSolved()需要一个回调作为第二个参数来将值传递回调用者。像这样:

router.get("/challenge/:challengeId", requireLogin, function(req, res) {

    var challengeId = req.params.challengeId;

    var isSolved = function(challengeId, callback){  // <<=== pass callback here
        console.log("in the aggregation: ", challengeId); // returns challengeId
        User.aggregate([
                    //var isSolved = User.aggregate([
                    { $match: {"solvedChallenges": { "challenge": challengeId } } },
                    { $project: {
                        userName: 1 }
                    }
                ],
                function(err, results){
                    console.log("this is the result: ", results); // logs a result if the there is one, and [] if there is no result.
                    callback(err, results); // <<=== call callback here to return
                });
    };

    //line below should return something like: []
    // or [ { _id: 56f5544bc171b1b8663bb15f, userName: 'John' } ]
    //console.log("is solved is: ", isSolved(challengeId));

    isSolved(challengeId, function(err, results) {
        if (err) {
            // return error here using res
        } else {
            // do something with results and 
            // return it using res
        }
    }); 
});