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

151
Views
Mongo DB Search and sort not working - collection.find(...).sort is not a function

I have a use case to search for a particular string on one field and return the results in sorted order based on another field. The below is the function I'm using in Node.js and the error being thrown.

router.get("/getappts/:username", function (req, res) {
  console.log(req.params.username)
  collection.find({ username: req.params.username }).sort( {date : 1} ), function (err, appointments) {
    if (err) throw err;
    
    console.log(appointments)
    res.json(appointments);
  } 
})

Error - collection.find(...).sort is not a function.

Not sure how to model the query.

But the below query on Mongo Compass seems to work fine -

enter image description here

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

0

might be where your callback is, I would suggest using promises instead

router.get("/getappts/:username", async function (req, res) {
  try {
    console.log(req.params.username)
    const appointments = await collection.find({ username: req.params.username }).sort({ date : 1 })
    
    console.log(appointments)
    res.json(appointments);
  } catch (err) {
    throw err;
  }
}
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!