猫鼬没有选择要渲染的回调变量

时间:2020-05-02 22:30:44

标签: node.js mongodb mongoose ejs

app.get("/users/:id", function (req, res) {
    User.findById(req.params.id, function (err, foundUser) {
        if (err) {
            console.log(err)
        } else {
            console.log(foundUser)
        }
    })
    Item.countDocuments({ UID: req.params.id }, function (err, itemCount) {
        if (err) {
            console.log(err)
        } else {
            console.log(itemCount)
        }
    })
    Item.find({ UID: req.params.id }, function (err, foundItems) {
        if (err) {
            console.log(err)
        } else {
            console.log(foundItems)
        }

    })
    res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount})

由于某种原因,它不会呈现,并一直说尽管存在上述回调,但变量不存在。使用EJS进行渲染。

2 个答案:

答案 0 :(得分:1)

我可能没有正确阅读代码,但是回调变量是否超出了res.render方法的范围? 您可能需要从每个Mongoose查询中返回回调,并将它们存储在res.render方法范围内的变量中。

答案 1 :(得分:0)

按照Richie的建议,您不能从外部作用域的回调内部访问变量。

app.get("/users/:id", function (req, res) { 
    User.findById(req.params.id, function (err, foundUser) { 
        if (err) { console.log(err) } 
        else {
            console.log(foundUser) 

            Item.countDocuments({ UID: req.params.id }, function (err, itemCount) { 
                if (err) { console.log(err) } 
                else { 
                    console.log(itemCount) 
                    Item.find({ UID: req.params.id }, function (err, foundItems){ 
                        if (err) { console.log(err) } 
                        else { 
                        console.log(foundItems);   
                        res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount})
                        } 
                    });
                } 
            }); 
        } 
    });
});

请注意,我已将res.render方法放在回调中,以便变量可以使用。

编辑

如Marcel Djaman所建议,您可能应该使用async/await使代码更具可读性。进一步了解async/await here

app.get("/users/:id", async function (req, res) { 
    try {
        const foundUser = await User.findById(req.params.id);
        console.log(foundUser) 

        const itemCount = await Item.countDocuments({ UID: req.params.id });
        console.log(itemCount) 

        const foundItems = await Item.find({ UID: req.params.id });
        console.log(foundItems);   
        res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount});
    } catch(err) {
        console.error(err)
    }
});

您会注意到此代码比上面的代码简单得多。