繁体   English   中英

如何检查MongoDB中是否存在选定的电子邮件和名称

[英]How to check if selected email & name is alread exist in MongoDB

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

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

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

                        }
                    })
            }
        })

有没有更短的写方法? 谢谢 :)

如果您使用的是Mongoose,则可以在模型中使用mongoose-unique-validator

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  name: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model('User', userSchema);

这样,如果Mongoose检测到您试图添加具有现有名称或电子邮件的用户,它将引发错误。

情况1-您需要一对是唯一的

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

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

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

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

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

个人推荐:按照@ will-alexander提供的解决方案,这样会更有效率。

如果您想在一个查询中使用两个键的唯一性

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

如果希望两个键在一个查询中分别唯一使用

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

暂无
暂无

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

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