简体   繁体   中英

MongoDB Error 'Cannot read property '_id' of undefined'

I'm setting up a web-app with chat rooms for teachers and their students. Teachers will invite their students to the program and therefore I need to validate whether the students have an account already.

I've scoured the internet for solutions but none of the solutions are for the same issue as mine

function insertUsers(collectionName, userArray) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('squeakdb');
        for (var i=0; i<userArray.length; i++) {
            dbo.collection(collectionName).find({ studentId: userArray[i].studentId }).toArray(function (err, res) {
                console.log(res == '');
                // If res == '' is true, it means the user does not already have an account
                if (res == '') {
                   dbo.collection(collectionName).insertOne(userArray[i], function(error, result) {
                       if (error) throw error;
                       console.log('Inserted'); 
                   }); 
                }
            });
        }
    });
}
insertUsers('userlist', [{ 'studentId': 'STU0001' }, { 'studentId': 'STU0018', 'firstName': 'testName' }]);

The expected result is for the first object in the array to not be inserted into the database, and for the second object to be inserted.

The current result is the first object not being inserted (as expected) and the second object producing the following error:

TypeError: Cannot read property '_id' of undefined

I've discovered why the error occurred, it was caused by doing an asynchronous call inside a for loop. Here is the fixed code.

function insertUsers(collectionName, userArray) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('squeakdb');
        userArray.forEach(function (index){
            dbo.collection(collectionName).find({ studentId: index.studentId }).toArray(function (err, res) {
                console.log(res.length == 0);
                if (res.length == 0) {
                   dbo.collection(collectionName).insertOne(index, function(error, result) {
                       if (error) throw error;
                       console.log('Inserted'); 
                   }); 
                }
            });
        });
    });
}

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