Home > Software design >  How to find email in MongoDB using NextJS and mongoose
How to find email in MongoDB using NextJS and mongoose

Time:09-20

I am trying to create a login endpoint that checks to see if an email is already stored in the database. If an email exists it will return an error, otherwise it notifies that an email exists. For some reason, User.findOne({ email: req.body.email }) does not seem to work. Here is the code I am currently using (located in pages/api/login.ts.)

import dbConnect from "../../lib/dbConnect";
import User from "../../models/User"
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
    await dbConnect()
    //type of request
    const {method} = req

    if (method === "POST") {
      try {
        await User.findOne({email: req.body.email}, function(err, user) {
          if (err) {
            res.status(400).json({error: "no email found"})
          }

          if (user) {
            res.status(200).json({success: "email found", data: user})
          }
        })
      } catch (error) {
        res.status(400).json({error: "connection error"})
      }
    }
}

CodePudding user response:

I never seen callback with await syntax:

try {
   const user = await User.findOne({ email: req.body.email });
   if (user) {
            res.status(200).json({success: "email found", data: user})
          }
} catch (error) {
  // handle error here
}
  • Related