【问题标题】:Using findOne() to query an email address使用 findOne() 查询电子邮件地址
【发布时间】:2016-07-05 18:13:49
【问题描述】:

我正在尝试在我的数据库中查询与用户输入匹配的电子邮件地址。我正在使用findOne(),但不知何故我遇到了问题:

Profile.findOne({emailaddress : req.body.emailaddress},   function(matchinguser) {
            console.dir("matching user" + matchinguser);
            Profile.create(req.params.all(), function (err, profile) {
                console.dir(profile);
                if (err) {
                    req.session.flash = {
                        err: err
                    }
                    return res.redirect('/profile/new')
                }
                res.redirect('/profile')
                req.session.flash = {};
            }) //profile created
        }) //findone

【问题讨论】:

  • 您的findOne() 回调函数缺少err 参数,它只有结果(matchinguser 参数)。尝试添加Profile.findOne({emailaddress : req.body.emailaddress}, function(err, matchinguser) { .. 看看效果如何。
  • “但不知何故我遇到了问题:” 展开所说的“问题”

标签: node.js mongodb sails.js


【解决方案1】:

我认为目前的代码存在一些问题。回调中缺少的“err”就是其中之一,但我认为您应该使用“exec”。现在,您的函数正尝试像在sails.js 中格式化本机查询一样执行。这是我推荐的调整代码:

Profile.findOne({emailaddress : req.body.emailaddress}).exec(err,function(matchinguser) {
     //Handle errors  
     if (err){ return res.negotiate(err);}

     //Handle success
     //I assume do some checks on the user found e.g. return them or if not found create the user
    if(!matchinguser){
     //No user found so redirect back
     return res.redirect('/profile');}
    //Rest of your code can go in here if needed I've just redirected you back for now.
    return res.redirect('/profile/);
    });

我也会小心在您的查询中直接使用 req.body.emailaddress 而不检查它,但这只是我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多