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

608
Visualizações
TypeError: Cannot read property '0' of undefined in post method in nodejs

I am new to nodejs and mongodb. I am trying to create simple to-do app with nodejs and mongodb. I have added the task in database. Now in post method, I am using insertOne method of mongodb and in res.json I am having the following error.

res.json(info.ops[0].data)
TypeError: Cannot read property '0' of undefined

Code :

app.post('/create-item', function(req, res){
    db.collection('items').insertOne({ text:req.body.text }, function(err, info){
      res.json(info.ops[0])
    })
}) 

Below is the screenshot of Error. Error Screenshot

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In current versions, there is no property returned named ops when insertOne is successful.

Hence the error TypeError: Cannot read property '0' of undefined

insertOne returns two properties:

acknowledged
Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined
insertedId
The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data

See:

  • InsertOne
  • InsertOneResult
app.post('/create-item', function(req, res){
    db.collection('items').insertOne({ text:req.body.text }, function(err, info){
      console.log(info.acknowledged)
       console.log(info.acknowledged)
      res.json(info.acknowledged)
    })
}) 

In previous versions, for example 3.2, different properties were returned for insertOne:

  • insertOne @3.2
  • insertOneWriteOpCallback @3.2

Similarly, different properties were returned for updateOne:

  • updateOne @3.2
  • updateOneWriteOpCallback @3.2

For more information about migrating to version 4 from earlier versions, see the article:

Changes in 4.x (and how to migrate!)

over 4 years ago · Santiago Trujillo Relatório

0

I encountered the same problem with the to-do app tutorial today. For those interested try changing the line - res.json(info.ops[0])

to - res.json({ _id: info.insertedId.toString(), text: req.body.text })

This gets the inserted id from the database for the newly added item. As "info" doesn't seem to return the inserted text in the current version of mongodb - i added that from the request parameter.

I got my information from here - Get the _id of inserted document in Mongo database in NodeJS

over 4 years ago · Santiago Trujillo Relatório

0

you are doing it wrong way firstly check the err then send the res.json because the error is because your info might be null if data not inserted successfully so you need to do it like

app.post('/create-item', function(req, res){
    db.collection('items').insertOne({ text:req.body.text }, function(err, info){
      if (err) {
           res.json({message: "not inserted successFully"});
           return;
       }
      res.json(info.ops[0])
    })
})

now in above code what will happen if data is not inserted successfully it will send the error as response and return from function.

over 4 years ago · Santiago Trujillo 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