[英]How to check whether a user exists in mongoose?
所以,我正在嘗試檢查是否有用戶我有以下代碼:
const userExist = await User.find({ username: req.body.username });
if (userExist)
return res.status(400).send({ message: "User already exists" });
但即使用戶不存在它仍然會給出錯誤User already exists
並且用戶存在 object 返回[]
你可以使用const user = await User.findOne({ username: req.body.username });
這只有一個,你可以檢查!用戶
原因是[]
在Javascript
中為真。 您需要檢查長度並檢查數組中是否有一些數據。
const userExist = await User.find({ username: req.body.username });
if (userExist.length > 0)
return res.status(400).send({ message: "User already exists" });
供將來參考,以下所有值在 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)
注意:建議您查看此鏈接。
另一種驗證用戶是否存在的方法是使用 mongoose .exist()
。 如果數據庫中至少存在一個與給定過濾器匹配的文檔,則 null 否則
在這里閱讀更多。存在
`
const userExist = await User.exists({ req.body.username });
if (userExist)
return res.status(400).send({ message: "User already exists" });
`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.