从数据库返回数据

时间:2018-08-20 14:39:27

标签: javascript json node.js mongoose

我需要有关此语法的帮助

var Category = require("../models/category");

app.get("/", function(req, res){

 var categories = findCategory();

 res.send(categories);
});

function findCategory() {
 Category.find({})
    .populate("subCategories")
    .exec(function(err, categories) {            
     if (err) {
      req.flash("error","Error while retrieving information from database");
      res.redirect("back");
     }
     return (categories);
  });
};

结果不确定。.我似乎不明白为什么

我应该退还

[ { subCategories: [ [Object], [Object], [Object] ],
_id: 5b58fe38a9281b21d07fc094,
title: 'Web, IT & Software Dev',
description: 'PHP, Wordpress, HTML, JavaScript and many more',
__v: 3 },
 { subCategories: [ [Object] ],
_id: 5b58fe4aa9281b21d07fc095,
title: 'Mobile Phones & Computing',
description: 'Mobile App Development, Android, iPhone, iPad, Amazon Kindle..',
__v: 1 },]

请帮助!!!谢谢

1 个答案:

答案 0 :(得分:2)

主要问题是您的findCategory函数在回调内返回一个值,但是您的路由像同步函数一样调用它。有几种解决方法,但是如果您使用的是现代版本的Node.js,我喜欢async/await。看起来像这样:

var Category = require("../models/category");

app.get("/", async function(req, res){
    try {
        var categories = await findCategory();
        res.send(categories);
    }
    catch(e){
        req.flash("error","Error while retrieving information from database");
        res.redirect("back");
    }
});

async function findCategory() {
    return await Category.find({})
      .populate("subCategories")
      .exec();
};

异步/等待本质上是一种以顺序方式编写异步代码的方式。

另一个问题是您在req.flash中有req.redirectfindCategory,但是如果遇到错误,就不会定义req