Estoy tratando de encontrar un documento en Mongoose usando findOne (no find), y quiero obtener el documento más reciente aunque tengan campos idénticos.
Por ejemplo, estos son los documentos en 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" }Así que necesito hacer una consulta en la línea de esto:
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" } */ Entonces, cuando busco Client.findOne por nombre, espero el documento más reciente. Sin embargo Client.findOne parece devolver el anterior.
¿Algún consejo?
pase el argumento como un sort: { 'created_at' : -1 } cambiando -1 a 1 obtendrá el registro más antiguo. Así que su nueva consulta se verá así
const client = Client.findOne({name: "John Smith"}).sort({created_at: -1});