I am currently learning how to use API routes in Next.js with sample data retrieved from MongoDB. My challenge lies in attempting to retrieve data from a single object, which is proving more difficult than expected as I am new to working with MongoDB.
After executing the following query, I am consistently faced with an empty array being returned:
import { connectToDatabase } from '../../../util/mongodb';
export default async (req, res) => {
const { db } = await connectToDatabase();
const movies = await db
.collection("movies")
.find({ "_id": "573a1395f29313caabce1f51" })
.limit(20)
.toArray();
res.json(movies);
};
The query should correspond to an object structured like this:
{
"_id": "573a1395f29313caabce1f51",
"fullplot": "some text goes here"
}
My dilemma now is figuring out what I am overlooking. Shouldn't
.find({_id: "573a1395f29313caabce1f51"})
successfully return the specified information? Why does it only produce an empty array? Although I understand why an array is returned due to the .toArray()
method, it shouldn't affect the outcome of the results.
It's worth mentioning that querying without any parameters functions correctly. There are no issues when running the following query:
import { connectToDatabase } from '../../util/mongodb';
export default async (req, res) => {
const { db } = await connectToDatabase();
const movies = await db
.collection("movies")
.find({})
.sort({ metacritic: -1 })
.limit(20)
.toArray();
res.json(movies);
};
Any insights or assistance provided would be greatly appreciated. Thank you in advance!