I know about Node.js's non blocking I/O and what are async functions but I'm having trouble to point down why this code runs like it runs.
I'm connecting to a MongoDB collection, searching for duplicates, putting the first values that repeat themselves in an array object (dupIndex). I see 2 values when the array prints (console.log(dupIndex);), but 0 when I use the .length property later (console.log(dupIndex.length);) -- when I'm actually expecting 2.
I would like to continue and manipulate the collection with the data I have in dupIndex (like use deleteMany method), but if it shows 0, I can't, at least not like this. Can someone explain this and help me with this?
Thanks!
//connect us to a running MongoDB server
const {MongoClient, ObjectID} = require('mongodb');
var dataBase = "TodoApp";
//connecting to a database
//connects to the database /TodoApp, if no such db exists it auto creates it
MongoClient.connect(`mongodb://localhost:27017/${dataBase}`, (err, db)=>{
if(err){
//return or 'else' - so if an error happens, it won't continue
return console.log(`Unable to connect. Error: ${err}`);
}
console.log(`Connected to MongoDB server. Database: ${dataBase}.`);
var dupIndex = [];
//find all
db.collection('Todos')
.find()
.toArray().then((docs) => {
for ( var i =0; i< docs.length -1; i++){
for(var j =i+1; j< docs.length; j++){
if(docs[i].text === docs[j].text)
{
console.log(`in`);
dupIndex.push(docs[i].text);
i++;
}
}
}
console.log(dupIndex);
}, (err)=> {
console.log(`unable t o fetch`);
});
console.log(dupIndex.length);
// for(var i = 0; dupIndex)
//close the connection to the db
db.close();
});