如何在 Mongoose 中使用 findOne 查找最新的(相同的)文档

How do I find most recent (identical) document with findOne in Mongoose

我正在尝试使用 findOne(不是 find)在 Mongoose 中查找文档,我想获取最新的文档,即使它们可能具有相同的字段。

例如,这些是 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"
}

所以我需要按照以下方式进行查询:

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"
}
*/

所以当我按名字 Client.findOne 时,我期待的是最新的文档。然而 Client.findOne 似乎只是 return 旧的。

有什么建议吗?

将参数作为对象传递 sort: { 'created_at' : -1 } 将 -1 更改为 1 将获取最早的记录 所以你的新查询看起来像

const client = Client.findOne({name: "John Smith"}).sort({created_at: -1});