Home > Net >  How to fix the Type Error: Cannot read properties of undefined (reading '0')?
How to fix the Type Error: Cannot read properties of undefined (reading '0')?

Time:11-30

Here is my function. Showing error on resolve(data.ops[0])

var db = require("../config/connection")
var collection = require("../config/collection")
const bcrypt = require('bcrypt')
module.exports={
    doSignup:(userData)=>{
        return new Promise(async(resolve,reject)=>{
            userData.Password =await bcrypt.hash(userData.Password,10)
           db.get().collection(collection.USER_COLLECTION).insertOne(userData).then((data)=>{
               resolve(data.ops[0])
           })
        })
    },
}
     

CodePudding user response:

Which version of Mongodb are you into?

Cause the new versions don't have an property called ops and that's why resolve(data.ops[0]) gives an error what you see.

Looking at the documentation below it returns a InsertOneResult

https://mongodb.github.io/node-mongodb-native/4.1/classes/Collection.html#insertOne

insertOne(doc: OptionalId<TSchema>): Promise<InsertOneResult<TSchema>>

If you see the document of same https://mongodb.github.io/node-mongodb-native/4.1/interfaces/InsertOneResult.html

It returns acknowledged and insertedid. Thus the below works

resolve(data.insertedId)
  • Related