【问题标题】:Mongodb findOne but check if request is empty firstMongodb findOne 但首先检查请求是否为空
【发布时间】:2016-02-25 19:48:17
【问题描述】:

我正在使用 Mongodb 和 findOne 功能:

User.findOne({$or: [{email: req.body.email}, {mobile: req.body.mobile}]}

但是我面临的问题是req.body.emailreq.body.mobile - 在某些情况下可能为空。

我最初使用以下方法解决了这个问题:

var toSearchSmartString = {$or: [{email: req.body.email}, {mobile: req.body.mobile}]};
if (req.body.email.length == 0) {
    toSearchSmartString = {mobile: req.body.mobile};
} else if (req.body.mobile.length == 0) {
    toSearchSmartString = {email: req.body.email};
}

然后在 findOne 中,只需使用:

User.findOne(toSearchSmartString);

所以我想检查一下这个“安全”的待办事项吗?我问这个安全的原因是因为如果我没有为 toSearchSmartString 设置默认值,而是在 if 块的末尾(在 else 中)设置它,我会得到字符串的“未定义”。

我担心 findOne 方法可能会在检查 if else 条件之前使用默认的 toSearchSmartString?我有理由担心这个吗?

或者有一些我可以用来解决的 Mongodb 函数吗?

更新: 因此,在 cmets 在下面回答之后 - 代码有问题:

我通过将上面的 var 声明移动到使用它的位置来解决它。

var contWithRegCallback = function(err, user) {
          console.log(user);
        }

    if (req.body.email.length == 0) {
          User.findOne({mobile: req.body.mobile}, contWithRegCallback);
        } else if (req.body.mobile.length == 0) {
          User.findOne({email: req.body.email}, contWithRegCallback);
        } else {
          User.findOne({$or: [{email: req.body.email}, {mobile: req.body.mobile}]}, contWithRegCallback);
        }

即回调函数中的用户一直返回未定义。应该是fineOne的内容吧?

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    你为什么不直接使用条件检查? 这个简单的 sn-p 应该可以按预期工作,请注意,您想通过电子邮件移动设备进行过滤。

    var callback = function(err, result){
        if(err) {
            return res.status(400).send({message: 'Server error:' + JSON.stringify(err)});
        } else {
            res.json(result);
        }
    }
    if (req.body.email){
        User.findOne({email: req.body.email}, callback);    
    } else if (req.body.mobile) {
        User.findOne({mobile: req.body.mobile}, callback);
    } else {
        return res.status(400).send({message: "Email or Mobile required"});
    }
    

    【讨论】:

    • 啊酷。这是有道理的,但是在那个调用中我是否调用了处理方法:var callback = new function() { console.log('continue from here'); } 如果是这样,那么我如何从 findOne 中获取结果?
    • 再次嗨,我一直在玩,但在获取用户方面遇到了问题 - 在我的回调函数中检查是否找到用户时(虽然 console.log)我一直看到未定义:
    • 我通过将上面的 var decalrtion 移动到使用它的位置来解决它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多