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

发布于 2025-01-10 10:01:44 字数 727 浏览 0 评论 0原文

我正在尝试使用 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 似乎只是返回旧的。

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东风软 2025-01-17 10:01:44

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

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

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});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文