Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
Mongo user exist validation

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!