In Next.js, I can’t get the mongoDB document on the same line of my query?


This Content is from Stack Overflow. Question asked by Rongeegee

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.


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?