Home > Mobile >  Return just single Object instead of Array in NEXT.JS and MongoDB
Return just single Object instead of Array in NEXT.JS and MongoDB

Time:10-06

How can i return single object for instead of array? Because i asking in api just for single "Event" I using MongoDB Next.js

I always getting

[{}]

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
  ); 

Here is a 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;

CodePudding user response:

You would want to call the method .findOne() rather than .find():

const selectedEvent = await Events.findOne({
    slug: slug
});
  • Related