javascript - Add extra fields dependent of other query to query result in mongodb, using mongojs -
i need make mongodb query , add field each 1 of results. field values depend of result of query.
i'm trying call nested query in server.js
code. it's not working because res.json(data)
called before data elements modified. suspect there's way want using nested query (or using foreach
or aggregate
) in db.js
code, lack of experience javascript/mongo didn't let me find solution.
any appreciated.
server.js
app.get("/get_users_list", function(req, res) { db.getusersbycity(req.query.city, function(err, data) { if (err) { res.send(err); } else { for(var in data) { var rec = data[i]; db.checkvisitation({'user_id': req.query.user_id, 'friend_id': rec.user_id}, function(inner_err, inner_data) { if (inner_data) { rec["visited"] = "true"; } else { rec["visited"] = "false"; } }); } res.json(data); } }); });
db.js
var checkvisitation = function(visitjson, callback) { db.visitations.findone(visitjson, callback); } var getusersbycity = function(city, callback) { db.users.find({'city': city}).toarray(callback); }
edit:
i able fix problem adding check inside inner callback:
if (i == data.length - 1) { res.json(data); }
you need call res.json after responses db. since requests asynchronous need organize code wait them finish. there 2 adopted approaches organize code asynchronous calls:
- use async.js https://github.com/caolan/async
- use promises https://github.com/kriskowal/q
i recommend start async since closer current code
Comments
Post a Comment