【问题标题】:Return data from database从数据库返回数据
【发布时间】:2019-01-26 17:26:10
【问题描述】:

我需要有关此语法的帮助

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 },]

请帮忙!!!谢谢

【问题讨论】:

标签: javascript json node.js mongoose


【解决方案1】:

主要问题是您的 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();
};

Async/await 本质上是一种按顺序编写异步代码的方式。

另一个问题是您在 findCategory 中有 req.flashreq.redirect,但如果遇到错误,则不会定义 req

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-11-21
    相关资源
    最近更新 更多