【问题标题】:How to check if email or phone already exists in mongodb database如何检查电子邮件或电话是否已存在于 mongodb 数据库中
【发布时间】:2021-08-30 09:13:07
【问题描述】:

我在检查 MongoDB 数据库中的电子邮件和电话号码时遇到问题。我的代码只检查电子邮件是否存在于数据库中,但不响应电话。

const express = require("express");
const router = express.Router();

require("../db/conn");
const User = require("../model/userSchema");

router.get("/", (req, res) => {
  res.send(`Hello World from server lolstar`);
});

router.post("/register", async (req, res) => {
  const { name, email, phone, work, password, cpassword } = req.body;

  if (!name || !email || !phone || !work || !password || !cpassword) {
    return res.status(422).json({ error: "Please fill your details" });
    }
    try {
        const userExist = await User.findOne({ email: email }, {phone: phone });
        if (userExist)
        {
             return res
          .status(422)
          .json({ error: "Email or Phone number already exists" });
        }
        
        const user = new User({ name, email, phone, work, password, cpassword });
        
        const userRegister = await user.save();
        if (userRegister)
        {
             res.status(201).json({ message: "User registered successfully" });
            }
      
    } catch (err) {
        console.log(err);
        
  }
  
});

module.exports = router;

我已经添加了我的 UserSchema 文件。我认为它没有错误,请检查这里是否有问题。我希望代码检查电子邮件和电话,然后将其用于身份验证。

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
    },
    phone: {
        type: Number,
        required: true,
    },
    work: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true,
    },
    cpassword: {
        type: String,
        required: true,
    }

})

const User = mongoose.model('USER', userSchema);

module.exports = User;

【问题讨论】:

  • 您能否更具体地说明您的问题,比“不接电话”更具体?预期的行为是什么,您观察到的行为是什么?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您想检查email OR phone 是否存在于数据库中。您当前的查询检查是否两者都存在。您应该使用$or 运算符进行查询,如下所示:

await User.findOne({ "$or": [ { email: email }, { phone: phone} ] });

【讨论】:

  • 我也试过这段代码,但没有用。
  • 你能在问题中添加你的模式模型吗?
  • 我已经添加了我的 userSchema
  • 我更新了我的答案。你能再试一次吗?
  • 欢迎。如果对您有帮助,也考虑接受我的回答。
猜你喜欢
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 2014-03-15
  • 2020-03-17
  • 1970-01-01
  • 2013-06-08
相关资源
最近更新 更多