i trying work twitter data in node , running road blocks think should related node style coding. block of code meant grab tweets, check if text in mongo , if not insert it.
the first stumbling block find on trying print out console iterate through each before starts iterating through cursor. think if clear may me going forward. enough info me out?
what have is:
t.get('statuses/user_timeline', options , function(err, data) { var db = mongoclient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) throw err; console.log("connected mongodb !"); mycollection = db.collection('test_collection2'); (var = 0; < data.length ; i++) { //let's wrap in loop docu = data[i]; //console.dir(data); console.dir(i); var cursor = mycollection.find({text : data[i].text}).limit(1); cursor.each(function(err, doc) { if (doc != null) { console.dir('doc not null'); console.dir(doc.text); } else { console.dir('doc null - inserting'); mycollection.insert(docu, function(err, records){ console.log("record added "+records.text); }); } }) } }); })
the problem because javascript async. loop finished before find function in mongo gives return value.
i following, or similar - explaine concept:
t.get('statuses/user_timeline', options , function(err, data) { var db = mongoclient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) throw err; console.log("connected mongodb !"); mycollection = db.collection('test_collection2'); var myfunction = function(correct_i,docu){ var cursor = mycollection.find({text : data[correct_i].text}).limit(1); cursor.each(function(err, doc) { if (doc != null) { console.dir('doc not null'); console.dir(doc.text); } else { console.dir('doc null - inserting'); mycollection.insert(docu, function(err, records){ console.log("record added "+records.text); }); } }) }; (var = 0; < data.length ; i++) { //let's wrap in loop docu = data[i]; //console.dir(data); console.dir(i); myfunction(i,docu); } }); }) this way each lookup/find mongo have correct i. because function gets parameter
Comments
Post a Comment