I tried the following on my Next.js backend, and I have MongoDB collection named "users". I want to find the user that has the maximum id.
const max_id = await users.find({}).sort({"id":-1}).limit(1).toArray()[0]["id"]
I get the error of unhandledRejection: TypeError: Cannot read properties of undefined (reading 'id') which indicates this entire statement returns none.
However, if I do the following in two lines, everything works as intended:
const newest_user = await users.find({}).sort({"id":-1}).limit(1).toArray();
const max_id = newest_user[0]["id"];
in my first example that doesn't work, is that because users.find({}).sort({"id":-1}).limit(1).toArray() is a promise, it will take time to resolve. But before the promise resolves, the promise's value is undefined, and undefined[0]["id"] will throw an error.
Please correct me.