如何返回单个对象而不是数组?因为我在api中只要求单个事件;我使用MongoDB + Next.js
我总是得到
({})
i Just want it get
{}
const fetchWithId = (url: RequestInfo) => fetch(url).then((r) => r.json());
const index = () => {
const router = useRouter();
const { data, error } = useSWR(
`http://localhost:3000/api/events/event?slug=${router.query.slug}`,
fetchWithId
);
这是一个Next API
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const {
method,
query: { slug},
} = req;
if (req.method !== 'GET') {
return;
}
await dbConnect();
const selectedEvent = await Events.find({
slug: slug,
});
res.status(200).json(selectedEvent);
};
export default handler;
您希望调用。findone()方法而不是。find():
const selectedEvent = await Events.findOne({
slug: slug
});