2

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

Hardik Leuwa
  • 3,282
  • 3
  • 14
  • 28
JDezzo
  • 21
  • 5
  • Possible duplicate of [TypeError: Cannot read property '\_id' of undefined](https://stackoverflow.com/questions/18542329/typeerror-cannot-read-property-id-of-undefined) – Syed mohamed aladeen Jul 04 '19 at 05:07
  • Solution in that post doesn't work, I tried it already – JDezzo Jul 04 '19 at 05:21
  • Which line does the Error occur? Side notes, `res` should be an array. It's better fro you to check the `length` property, instead of comparing with empty string. – chakwok Jul 04 '19 at 06:01
  • The error occurs on line 10 – JDezzo Jul 04 '19 at 06:19
  • 1
    possibly because you are trying to do an asynchronous call inside for loop, have a look on this: https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop – Mohammed Amir Ansari Jul 04 '19 at 10:00
  • That's what it looks like to me too. Switching to use `async/await` might make things a bit simpler, or if you want to stick with callbacks, coalan's async library is pretty nice. – klhr Jul 04 '19 at 10:01

1 Answers1

0

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'); 
                   }); 
                }
            });
        });
    });
}
JDezzo
  • 21
  • 5