简体   繁体   中英

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

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])
           })
        })
    },
}
     

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM