Entonces, estoy tratando de verificar si hay un usuario o no. Tengo el siguiente código:
const userExist = await User.find({ username: req.body.username }); if (userExist) return res.status(400).send({ message: "User already exists" }); pero incluso si el usuario no existe, todavía da el error User already exists y el objeto userExists devuelve []
puedes usar const user = await User.findOne({ username: req.body.username }); esto obtiene solo uno y puedes verificar! usuario
La razón es [] es cierto en Javascript . Debe verificar la longitud y verificar si hay algunos datos en una matriz.
const userExist = await User.find({ username: req.body.username }); if (userExist.length > 0) return res.status(400).send({ message: "User already exists" });Para referencias futuras, todos los valores a continuación son verdaderos en 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)Nota: Le recomendamos que consulte este enlace.