One of the API routes in Next has been causing some issues. Here is the code:
import {NextApiRequest, NextApiResponse} from "next";
import dbConnect from "../../utils/dbConnect";
import {UserModel} from "../../models/user";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405);
if (!req.query.id || Array.isArray(req.query.id)) return res.status(406).json({message: "No ID found in request"});
try {
await dbConnect();
const user = await UserModel.findOne({ _id: req.query.id });
if (!user) return res.status(404).json({message: "No user found"});
return res.status(200).json({data: user});
} catch (e) {
return res.status(500).json({message: e});
}
}
There seems to be an error indicated by Typescript on the line
const user = await UserModel.findOne({ _id: req.query.id });
, saying Type 'string' is not assignable to type 'Condition<UserObj>'
. Even when trying a different approach using ObjectId
instead of a string (const user = await UserModel.findOne({ _id: mongoose.Types.ObjectId(req.query.id) });
), the same error persists.
The documentation and type files have been checked, but it's still unclear why this issue is occurring. Isn't querying by ID with a string or ObjectId considered a valid condition object? Queries based on other fields seem to work without any problems.
If anyone can shed some light on why this is happening and suggest a solution, it would be greatly appreciated.