Upon adding data to mongodb, an error message is displayed stating "Cannot read property '_id' of undefined."

Backend Server-Side Code

The following is my server-side code. Below it, you can find the client-side code along with the error that is being displayed. I am having trouble identifying what the issue might be.

app.post("/service", async (res, req) => {
          const newService = req.body;
          const result = await databaseCollection.insertOne(newService);
          res.send(result);
        });

Frontend Client-Side Code

fetch("http://localhost:5000/service", {
      method: "POST", // or 'PUT'
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then((result) => {
        console.log("Success:", result);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  };

Error Details

(node:5388) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined
    at E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\operations\common_functions.js:64:17
    at Array.map (<anonymous>)
    at prepareDocs (E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\operations\common_functions.js:63:17)
    at new InsertOneOperation (E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\operations\insert.js:42:74)
    at Collection.insertOne (E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\collection.js:149:64)
    at E:\htmll\Assignment_11\Server\myapp\index.js:37:47
    at Layer.handle [as handle_request] (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\layer.js:95:5)
(node:5388) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

Answer №1

Instead of using the insertOne method, try utilizing the save method by first instantiating your object with

new databaseCollection(newService)
. Afterwards, you can call the save method to insert your collection.

To ensure that the Content-Type is JSON, opt for res.json over res.send.

Your revised code should resemble the following:

app.post("/service", async (res, req) => {
    const newService = req.body;
    try {
        const service= await new databaseCollection(newService);
        const savedService=await service.save()
        res.status(200).json(savedService);
    } catch (err) {
        res.status(500).json(err);
    }
});

Answer №2

app.post("/service", async (res, req) => {
  const newResult = await new databaseCollection(createdService)
  await newResult.save()
  res.send(newResult);
});

Give this approach a try.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message states: `res.Send function is not recognized as a valid

Recently, I've been working on a function that goes like this: app.get('/counter', function (req, res) { console.log('/counter Request'); var counter = 0; fs.readFile(COUNTER_FILE_NAME, function(err, data) { c ...

Unable to display Boostrap modal upon clicking href link

Can someone help me troubleshoot why my pop modal is not displaying after a user clicks on a specific link on my webpage? I have attempted the following: <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></s ...

Facing an issue with Axios requests in React JavaScript

I need help with my Node.js data retrieval process. It seems like there are too many requests being made (around 5000) which is causing the server to slow down and some images on other pages aren't even loading. Should I consider limiting the number o ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

I'm having trouble resolving 'fs' within my Next.js api route

When attempting to use the fs module within my api route file for filesystem operations, I encountered an error message: Module not found: Can't resolve 'fs'. This issue not only prevents me from utilizing fs in my handler function but also ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Is there a way to retrieve a session variable within an EJS view template?

After a user logs in, I would like to store their details in the session and be able to access them in ejs templates. How can this be accomplished? app.post('/registration', function(req, res) { var name = req.session.user_name = req.body.us ...

Issue: Unable to locate module 'js-yaml' while executing npm start command

Unable to locate module 'js-yaml' Require stack: D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\loaders.js D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\createExplore ...

What could be causing the JSON.parse() function to fail in my program?

Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Having trouble getting rid of the border-bottom?

I have been attempting to customize the appearance of the React Material UI tabs in order to achieve a design similar to this: https://i.stack.imgur.com/tBS1K.png My efforts involved setting box-shadow for the selected tab and removing the bottom border. ...

I am attempting to enable automatic login in npm through a bash script, but I am unsure of how to input the username and password when prompted. Is there a way to achieve this?

I am currently working on a bash script to automate the installation of nodejs and setting up a private npm registry. So far, everything has been going smoothly until I encountered the following hurdle: Configuring the npm Registry: To set the npm regist ...

Is the user consistently experiencing redirection to a failure page with passport?

I've been struggling with the user login redirection issue on my website. No matter what changes I make, it keeps redirecting to failure instead of success. I'm not sure if I missed something or did something wrong. The documentation for passport ...

Leveraging Angular 6: Implementing custom scripts on a component basis and verifying their presence

I need some help with a script that I want to run on a specific component only. I've managed to add the script to the component, but there are a few issues that I'm unsure how to fix. When I go to the component, the script is added to the DOM b ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...

Relocating the node_modules folder results in syntax errors arising

I encountered a perplexing syntax error issue. I noticed that having a node_modules directory in the same location I run npm run tsc resolves the issue with no syntax errors. However, after relocating the node_modules directory to my home directory, ~ , a ...

Generate a new span element within a div element programmatically using Vuex

I have integrated an existing web application developed using vue.js. Below is the code snippet: function () { var e = this, t = e.$createElement, n = e._self._c || t; return e.messag ...

The request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

Most efficient method: Exporting a DynamoDB table to a CSV file and saving it in an S3 bucket

Is there a more efficient way to export a DynamoDB table into an S3 bucket in CSV format? We already have a lambda function set up to update the DynamoDB table, but now we need to export the entire table. I came across a method of streaming directly from ...

Retrieve the original content of a file uploaded by a user in Node.js using Express

Can we extract the raw file contents from a user uploaded file using Node.js Express? app.post('/images', upload.single('image'), async (req, res) => { const file = req.file ... I have come to realize that the file variable in t ...