javascript - How to check whether a user exists in mongoose? - Stack Overflow

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

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 []

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 []

Share Improve this question edited Dec 1, 2021 at 7:50 Apoorva Chikara 8,8033 gold badges23 silver badges38 bronze badges asked Dec 1, 2021 at 7:48 Shahab AtharShahab Athar 1201 gold badge4 silver badges15 bronze badges 2
  • Use User.findOne instead of User.find – Arif Khan Commented Dec 1, 2021 at 7:53
  • @Shahab Make sure to use findOne. find method goes through the entire database to find as many records as possible whereas findOne stops as soon as it finds the first match. – Molda Commented Dec 1, 2021 at 8:24
Add a ment  | 

3 Answers 3

Reset to default 3

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" });

`

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: Remend you to check this link.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744742617a4591117.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信