Module.exports函数不返回Node.js

时间:2018-04-08 09:32:41

标签: javascript node.js mongodb express

我创建了module.exports函数,

const mongoose = require("mongoose");
const Loan = require("../models/loan_model");

function unpaidList() {
  Loan.aggregate([
    {
      $group: {
        _id: "$ePaidunpaid",
        data: { $push: "$$ROOT" },
        count: { $sum: 1 }
      }
    }
  ]).then(function(data){
    console.log(data) // i am getting data here
    return data;
  })
}

 module.exports = { unpaidList };

这就是我调用函数的方式。

const unpaidListReq = require("../services/unpaidlist")
router.get("/", ensureAuthenticated,(req, res) => {
     let data = unpaidListReq.unpaidList()
     console.log(data)
      res.render("dashboard", {
        admin: req.user.eUserType,
        user: req.user,
      });
    })

但作为回报,在Consoling数据时,它返回undefined。 我看看之前提出的问题,但仍然得到这个。

1 个答案:

答案 0 :(得分:0)

unpaidList改为Promise

function unpaidList () {
  return Loan.aggregate([
    {
      $group: {
        _id: "$ePaidunpaid",
        data: { $push: "$$ROOT" },
        count: { $sum: 1 }
      }
    }
  ])
}

在您的处理程序中,您可以执行以下操作:

unpaidListReq.unpaidList().then(function (data) {
  res.render("dashboard", {
    admin: req.user.eUserType,
    user: req.user
  })
})