Home > OS >  Is mongoose findOne guaranteed to return the latest inserted doc it finds?
Is mongoose findOne guaranteed to return the latest inserted doc it finds?

Time:07-19

I have the following in the database:

username: Murat1010
firstName: Murat
lastName: Paşa
city: İstanbul
createdAt: 2022-07-15T23:24:32.382 00:00

username: Ömer98
firstName: Ömer
lastName: Demir
city: İstanbul
createdAt: 2022-07-15T23:25:00.023 00:00


username: Yaser334
firstName: Yasser
lastName: Tayyar
city: İstanbul
createdAt: 2022-07-15T23:27:59.688 00:00

I have the following Mongoose code:

const newestMember = await Users.findOne({city: "İstanbul"})

Is newestMember guaranteed to return Murat's Doc? guaranteed to return the newest one? can I stick to findOne? If it's not correct, then how?

CodePudding user response:

No it's not guaranteed. Read here I would do:

const newestMember = await Users.findOne({city: "İstanbul"}).sort({createdAt: -1})
  • Related