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?
CodePudding user response:
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});