Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda