简体   繁体   English

Express.js +猫鼬。 find()未传递定义变量的结果

[英]Express.js + Mongoose. find() not passing results for defined variable

I am trying to set items to be viewed only by the user that posted it. 我试图将项目设置为仅由发布它的用户查看。 I'm using Passport.js to take care of the sessions. 我正在使用Passport.js来处理会话。 In this code I am able to see everything successfully run up until the end. 在这段代码中,我能够看到一切成功运行到最后。

     app.get('/latestproject', isLoggedIn, function(req, res) { 
        var Project = require('../app/models/project');
        var latest = null;
        var currentUser = req.user._id;
        Project.find({owner: currentUser}).sort({_id: 'desc'}).limit(1).exec(
            function(err, projects) {
                if (err) {
                    res.send(err);
                } else if (projects) {
                    latest = projects._id
                    res.redirect('/project/' + latest);
                } else {
                    res.redirect('/start');
                }

            });
});

I've been able to run this identical code with no problems without the user component. 没有用户组件,我已经能够毫无问题地运行相同的代码。 The owner value in the database is the same as what is being output by the currentUser variable. 数据库中的所有者值与currentUser变量正在输出的值相同。

Everything seems to work fine but for some reason by the time it makes it down the pipe to my conditionals, I get "project/undefined" in the console log as my final result. 一切似乎都可以正常工作,但是由于某种原因,当它使之成为条件时,我在控制台日志中得到了“项目/未定义”作为最终结果。

I know it's probably something small, but I've been going for hours and I need help! 我知道这可能很小,但是我已经去了几个小时,需要帮助!

There is small mistake in your code. 您的代码中有小错误。 Normally mongoose find returns an array of objects even if the result count is 1. So change your code to this 通常,即使结果计数为1,猫鼬find也会返回对象数组。因此,将代码更改为此

else if (projects && projects.length===1) {
                latest = projects[0]._id
                res.redirect('/project/' + latest);
            } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM