Home > other >  MongoDB struggling to update DB
MongoDB struggling to update DB

Time:10-05

I'm new to MongoDB. I have a DB where cards data will be stored and update counts if the user likes the cards. Giving me a total likes number.

I keep getting my res as a 400 and I can't work out why. I got the update method to work manually. but when I put it into a function it does not work.

I'm using NEXT JS API routes.

import dbConnect from "../../utils/dbConnect";
import FavSchema from "../../models/FavoriteModel";

dbConnect();

export default async (req, res) => {
  const { method } = req;

  switch (method) {
    case "GET":
      try {
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;
    case "POST":
      try {
        const query = {
          cardId: req.body.cardHandler,
        };

        await FavSchema.findOneAndUpdate(
          query,
          { $inc: { favCount: 1 } },
          { upsert: true }
        );
        res.send("Succesfully saved.");
      } catch (error) {
        res.send(400, { error: "Error" });
      }
  }
};

function

 const handleCardFavClick = (id) => {
    const cardHandler = {
      id,
    };
    fetch("/api/favcounter", {
      method: "POST",
      body: JSON.stringify(cardHandler),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => console.log(data));
    dispatch(makeFav(cardHandler));
  };

Thank you!

CodePudding user response:

You are passing

{ id: "<id>" } 

as body in your API and reading "cardHandler" from req.body, which is "undefined".

In your POST API, replace

const query = {
      cardId: req.body.cardHandler,
    }

with

const query = {
      cardId: req.body.id
    }
  • Related