如何检查是否选择了电子邮件名称已经存在于MongoDB中 [英] How to check if selected email & name is alread exist in MongoDB

查看:104
本文介绍了如何检查是否选择了电子邮件名称已经存在于MongoDB中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果选择了用户电子邮件,我想获取信息.名称已经存在于MongoDB数据库中的某个位置.我想使电子邮件和名称唯一,因此不能重复使用这两个值.

I would like to get information if selected user email & name already exist somewhere in MongoDB database. I want to make email and name unique, therefore it couldn't be duplicates of both those values.

我已经写了工作代码,但是我想知道这种解决方案是否是最佳选择.

I already wrote working code, but I would like to know if this solution is optimal.

User.find({ email: email })
        .then(user => {
            if (user.length >= 1) {
                return res.status(409).json({
                    message: 'Mail exists'
                })
            } else {
                User.find({ name: name })
                    .then(user => {
                        if (user.length >= 1) {
                            return res.status(409).json({
                                message: 'Name exist'
                            })
                        } else {

                         // SOME CODE HERE

                        }
                    })
            }
        })

有没有更短的书写方式?谢谢:)

Is there any shorter way to write this? Thanks :)

推荐答案

案例1 -您需要配对对是唯一的

Case 1 - You need the pair to be unique

在这种情况下,该对(电子邮件,名称)将是唯一的.可以使用 AND 查询来完成.

In this case the pair (email,name) will be unique. This can be done using AND query.

User.find({email:email,name:name})

案例2 -您不需要电子邮件或姓名出现两次

Case 2 - You do not need either email or name appear twice

这可能会引起一些问题,因为可能有两个人名字相同但电子邮件不同.可以使用 OR 查询来满足此条件.

This can cause some issues since there can be two people with same name but different email. This condition can be met using OR querying.

User.find({$or:[{email:email},{name:name}]}

个人推荐:按照@ will-alexander提供的解决方案进行操作.

这篇关于如何检查是否选择了电子邮件名称已经存在于MongoDB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆