I am trying to perform a sign up form into Mongo Node.js and Express.js. I have already completed the task which inserts a document into users collection for a new user. But I need to create a validation if a user exist based on username or email as keys.
For example I am submitting a user:
{ "_id": { "$oid": "62ac54c4cd1c80d0e8e2f68a" }, "firstName": "test", "lastName": "test", "email": "test@test.com", "password": "test", "username": "test"}
If I try to sumbit the same creds in the sign up form, my API completely crashes with error code:
db.collection(...).exists is not a function
Note: I am using mongoose
Code:
app.post("/login", async (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const username = req.body.username;
var data = {
"firstName": firstName,
"lastName": lastName,
"email": email,
"password": password,
"username": username
}
console.log(data);
let userExist = await db.collection('users').exists({ "username": username, "email": email })
console.log(userExist);
if (userExist) {
console.log("User already exists");
return res.render('login');
} else {
db.collection('users').insertOne(data, function (err, collection) {if (err) throw err;});
}
res.render('login', { 'data': data });
});
Any ideas?
I see you are trying to find if user exists in the collection via two fields which are username and email.
With mongoose you could actually do it in many ways and the most better approach is to define your model, https://mongoosejs.com/docs/models.html
If you want to stick with your case then you could try this:
db.collection('users').find({ "username": username, "email": email })