javascript - Manipulating a list inside of a mongodb query -
first question here right...
the jest of i'm trying add list inside of query , able pass list on client node.js. code (simplified) follows:
socket.on('get_new', function() { var db = require('mongojs').connect('test', ['col1']); var db2 = require('mongojs').connect('test', ['col2']); db.col1.find( function(err, tups) { var total = []; if ( err || !rows ) { console.log("error") }; else { for(row in tups){ var id = row['id']; db2.col2.find({name:id}, function(foo, bar){ if ( foo || !bar ) { console.log("error") }; else { total += { name : bar['age'] }; console.log(total); //prints [ {alex:'20'}] } } } } console.log(total); // prints [] } } as showed in code, have put console.log statements see value , different inside of query vs after. i'm guessing has scope of code, seems me if after db.test2.find run, happened inside doesn't exist outside, don't why. in advance!
the code asynchronous. means in practice last statement: console.log(total); executed before first. print actual total you'd want wrap code in function this:
function myfnfortotal(notifytotal) { /* code above else */ total += sometotal; console.log(total); //prints [ {alex:'20'}] notifytotal(total); /* code below else */ } myfnfortotal(function(total) { console.log(total); });
Comments
Post a Comment