Skip to content
Advertisement

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

Answer

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:

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:

Similarly, different properties were returned for updateOne:

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

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

Advertisement