DEV Community

ivkeMilioner
ivkeMilioner

Posted on • Updated on

Problem with req. query;

I'm trying to pull data from a document containing a logged-in user from the MongoDB database. However, req. query doesn't seem to pass.

API:

export default async function handler(req, res) {
  const client = await clientPromise;
  const db = client.db("USERS");
  const { userName } = req.query;
  switch (req.method) {
  case "POST": {
    const bodyObject = JSON.parse(req.body);
    const query = {
      user: bodyObject.user,
      avatar: bodyObject.avatar,
      level: bodyObject.level,
    };
    const update = { $set: { score: bodyObject.score } };
    const options = { upsert: true };

    const newScore = await db
      .collection("USERS")
      .findOneAndUpdate(query, update, options);

    res.json(newScore);
    break;
  }
  case "GET": {
    const users = await db
      .collection("USERS")
      .find({ user: { $in: [userName] } })
      .toArray();
    res.json(users);
    break;
  }

  default: {
    // do nothing
  }
  }
}
Enter fullscreen mode Exit fullscreen mode

COMPONENT:

import styles from '../styles/Elements.module.css';
import clientPromise from '../lib/mongodb';


export default function ScoreHeader({ users }) {
  console.log(users)

  return (
    <div className={styles.containerIndex}>
     fadsfds
    </div>
  );
}

export async function getServerSideProps({}) {
  const client = await clientPromise;
 const db = client.db('USERS');

  const res = await fetch(`http://localhost:3000/api/usersAPI`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const users = await res.json();

  return {
    props: { users },
  };
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)