Mongodb Next Js - CRUD API Routes - Put request failing 500 error

Hello,

Apologies if my bug is very entry-level, I have been a developer for less than 6 months!

I am trying to perfom a PUT request through an API route on Next js (node js), however it keep failing and return a 500 error.

I have tried to debug it while following MongoDb documentation about CRUD, but I cannot find the issue.

It seems that the error comes from this part of the API route:

try {
      // Inspiration for this version: https://www.mongodb.com/docs/drivers/node/v3.6/usage-examples/updateOne/
      const db = client.db("main");
      // create a filter for a movie to update
      const filter = { _id: mongodb.ObjectID(updatedCompany.id) };

      // create a document that sets the plot of the movie
      const updateDoc = {
        $set: {
          name: updatedCompany.name,
          // slug: updatedCompany.slug,
          // size: updatedCompany.size,
          // bio: updatedCompany.bio,
          // location: updatedCompany.location,
          // image: updatedCompany.image,
          // website: updatedCompany.website,
          // industry: updatedCompany.industry,
          // userId: updatedCompany.userId,
          // email: updatedCompany.email,
        },
      };

      // this option instructs the method to create a document if no documents match the filter
      const options = { upsert: true };

      console.log(updatedCompany.id);

      const result = await db
        .collection("companies")
        .updateOne(filter, updateDoc, options);

      console.log(result);

      // Not sure about that line:
      // newCompany.id = result.insertedId;
    } 

Full api/companies/update root:

import { MongoClient } from "mongodb";
// import clientPromise from "../../../lib/mongodb";

// ON GOING

async function handler(req, res) {
  if (req.method === "PUT") {
    const {
      id,
      name,
      bio,
      size,
      location,
      image,
      website,
      industry,
      userId,
      email,
    } = req.body;

    // | (bio.trim() === "")
    // BACKEND VALIDATION
    if (!name || name.trim() === "") {
      res.status(422).json({ message: "Invalid input." });
      return;
    }

    function capitalize(word) {
      return word[0].toUpperCase() + word.slice(1).toLowerCase();
    }

    // Storing it in the database
    const updatedCompany = {
      id,
      name: capitalize(name),
      slug: name.toLowerCase().replace(/\s+/g, ""),
      size,
      bio,
      location,
      image,
      website,
      industry,
      userId,
      email,
    };

    let client;

    console.log(updatedCompany);
    console.log("Test ligne 51");
    console.log(updatedCompany.id);
    try {
      client = await MongoClient.connect(process.env.MONGODB_URI);
    } catch (error) {
      console.log("erreur 500 DB connection");
      res.status(500).json({ message: "Could not connect to database." });
      return;
    }

    const db = client.db("main");

    try {
      // Inspiration for this version: https://www.mongodb.com/docs/drivers/node/v3.6/usage-examples/updateOne/
      // create a filter for a movie to update
      const filter = { _id: mongodb.ObjectID(updatedCompany.id) };

      // create a document that sets the plot of the movie
      const updateDoc = {
        $set: {
          name: updatedCompany.name,
          // slug: updatedCompany.slug,
          // size: updatedCompany.size,
          // bio: updatedCompany.bio,
          // location: updatedCompany.location,
          // image: updatedCompany.image,
          // website: updatedCompany.website,
          // industry: updatedCompany.industry,
          // userId: updatedCompany.userId,
          // email: updatedCompany.email,
        },
      };

      // this option instructs the method to create a document if no documents match the filter
      const options = { upsert: true };

      console.log(updatedCompany.id);

      const result = await db
        .collection("companies")
        .updateOne(filter, updateDoc, options);

      console.log(result);

      // Not sure about that line:
      // newCompany.id = result.insertedId;
    } catch (error) {
      console.log("erreur 500 de storing");
      client.close();
      res.status(500).json({ message: "Storing message failed!" });
      return;
    }

    client.close();

    res.status(201).json({ message: "Sucessfuly stored company" });
  }
}

export default handler;

Thanks in advance for your help!!

it would be better helpfull if you also elevate errors’ messages and share them here.

by the way, I am not sure if related, but you use this line twice, inside and outside try block: const db = client.db("main");

Hello @Yilmaz_Durmaz, appreciate your quick response!

There is the error message:

Yes I have tried to put the client.db inside the try to see if it changes something, it did not, I have tried both scenario in vain, I have removed the duplicate, thanks

you misunderstood me. show whole error message, preferred on the server side since you don’t send a useful full error message back to browser. edit like this and copy error from server console:

    } catch (error) {
      console.log("internal error");
      console.dir(error);  // print on server console
      res.status(500).json({ message: "Internal error", error: error }); // not needed, only if you need in client side
      return;
    }

PS: you have 2 locations sendin 500 error. adapt this to both.

1 Like

Gotcha, thanks, I have made the edit, which allowed me to unbug my code!
It confirmed what I have found in the meantime, the issue comes from wrongly importing ObjectId that blocked me from executing:

const filter = { _id: ObjectId(updatedCompany.id) };

Now it is good.
Thanks man :smiley:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.