如何在 Mongoose 中使用 findOne 查找最新(相同)文档
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将参数作为对象传递
sort: { 'created_at' : -1 }
将 -1 更改为 1 将获取最旧的记录所以你的新查询看起来像
pass the argument as an Object
sort: { 'created_at' : -1 }
changing -1 to 1 will fetch the oldest recordSo your new query will look like