简体   繁体   中英

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

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;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM