Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

625
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda