'Check if a user already exists in mongodb database

I was trying to check if a user already exists in the database in a signup form. If a user already exists then the api route was supposed to return a message saying "User already exists" but if the user did not already exist then the data of the new user was supposed to be added to the mongodb database. In the below code it is always returning "User already exists" even though they don't exist in the database.

import { connectToDatabase } from '../../../lib/db';
import { hashPassword } from '../../../lib/auth';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const client = await connectToDatabase();
    const db = client.db();

    const data = req.body;
    const { email, password } = data;

    const existingUser = db.collection('users').findOne({ email: email });
    if (existingUser) {
      res.json({ message: 'User already exists', existingUser: existingUser });
      client.close();
      return;
    } //checks if user already exists

    if (
      !email ||
      !email.includes('@') ||
      !email.includes('.') ||
      !password ||
      password.trim().length < 7
    ) {
      res.status(422).json({ message: 'Invalid email or password' });
      return;
    }

    const hashedPassword = await hashPassword(password);
    await db.collection('users').insertOne({
      email: email,
      password: hashedPassword,
    });
    res.status(201).json({ message: 'Created user' });
    client.close();
  }
}



Solution 1:[1]

What does const existingUser = db.collection('users').findOne({ email: email }); evaluate to? Might be getting an empty object and not NULL as expected.

Something like

if (existingUser && Object.keys(existingUser).length()) {

might be what you are after.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 moogs