Shahab Athar
Shahab Athar

Reputation: 120

How to check whether a user exists in mongoose?

So, I am trying to check whether there is a user or not I have the following code:

const userExist = await User.find({ username: req.body.username });
if (userExist)
   return res.status(400).send({ message: "User already exists" });

but even if the user doesn't exist it still gives the error User already exists and the userExists object return []

Upvotes: 1

Views: 4320

Answers (3)

jauntyCoder
jauntyCoder

Reputation: 63

Another way to verify if the user exists is to use mongoose .exist(). If at least one document exists in the database that matches the given filter, and null otherwise

Read more here .exists

`

 const userExist = await User.exists({ req.body.username });

  if (userExist)
          return res.status(400).send({ message: "User already exists" });

`

Upvotes: 3

Nhut Pham
Nhut Pham

Reputation: 185

u can use const user = await User.findOne({ username: req.body.username }); this get only one and u can check !user

Upvotes: 2

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

The reason is [] is true in Javascript. You need to check the length and check if there is some data in an array.

const userExist = await User.find({ username: req.body.username });
if (userExist.length > 0)
     return res.status(400).send({ message: "User already exists" });

For future references, all the below values are truthy in JS.

if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

Note: Recommend you to check this link.

Upvotes: 2

Related Questions