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