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

119
Visualizações
How do I find most recent (identical) document with findOne in Mongoose

I am trying to find a document in Mongoose by using findOne ( not find ), and I want to get the most recent document even though they may have identical fields.

For example, these are the documents in Mongoose:

// Let's say this one was created a week ago in Mongoose
{
  name: "John Smith",
  age: 27,
  industry: "finance"
}

// This one was created this morning
{
  name: "John Smith",
  age: 27,
  industry: "healthcare"
}

So I need to do a query along the lines of this:

const client = await Client.findOne({name: "John Smith"});

console.log(client);

/* 
result: 
{
  name: "John Smith",
  age: 27,
  industry: "finance"
} 

expected: 
{
  name: "John Smith",
  age: 27,
  industry: "healthcare"
}
*/

So when I Client.findOne by name, I'm expecting the most recent document. However Client.findOne seems to just return the old one.

Any advice?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

pass the argument as an Object sort: { 'created_at' : -1 } changing -1 to 1 will fetch the oldest record So your new query will look like

const client = Client.findOne({name: "John Smith"}).sort({created_at: -1});
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