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

319
Views
Mongoose - find() not returning anything when no parameters are passed, but returns data when parameters are passed

I have the following model in teamMembers.js:

const { Schema, model } = require('mongoose');

const teamMembersSchema = new Schema({
    uid: String,
    name: String,
    hours: Number
})

const TeamMembers = model('teamMembers', TeamMembersSchema);

module.exports = TeamMembers;

I've created the following endpoints in teamMemberRoute.js:

const TeamMembers = require('./models/teamMembers');

module.exports = (app) => {

    app.get('/api/pods/teamMembers/:uid', async (req, res) => {
        let teamMember = await TeamMembers.find( {'uid': req.params.uid } );
        return res.status(200).send(teamMember);
    });

    app.get('/api/pods/teamMembers', async (req, res) => {
        let teamMembers = await TeamMembers.find();
        return res.status(200).send(teamMembers);       
    });
}

The first endpoint (/api/pods/teamMembers/:uid) works just fine - when I pass a uid it returns documents specific to that uid in the TeamMember collection.

The second endpoint should return all documents from the TeamMember collection since no parameters are passed. However, when the request is executed, only [] is returned. We know for a fact that documents exist in the TeamMember collection, since the first endpoint returns data from that collection based on the uid parameter that is passed.

I'm stumped on this. Any ideas? I don't think there is anything wrong with my model since I am able to execute the first endpoint with no issues.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Express executes code from top to button, and that is the reason for this issue. It will match your first endpoint and assume that uid is null. Just change the order of defined endpoints, like this:

module.exports = (app) => {

    app.get('/api/pods/teamMembers', async (req, res) => {
        let teamMembers = await TeamMembers.find();
        return res.status(200).send(teamMembers);       
    });

    app.get('/api/pods/teamMembers/:uid', async (req, res) => {
        let teamMember = await TeamMembers.find( {'uid': req.params.uid } );
        return res.status(200).send(teamMember);
    });

}
over 4 years ago · Santiago Trujillo 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!