Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
After inserting data on mongodb it shows me Cannot read property '_id' of undefined

server-side Code

Here you can see this is my server-side code and it's below i have put my client-side code and what error is showing. And I can't catch what's wrong here

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

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 Is

(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)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

Try this method.

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use save method instead of insertOne first instantiate your object by adding new databaseCollection(newService). and after that call save method to insert your collection

Use res.json instead of res.send to enforce Content-Type to be of JSON type

Your code should look like this:

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);
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda