I have a post request which I need to loop through an array, find the users in the database and sent the results back to the view but I can only seem to send back the first user. How are for-loops supposed to be implemented? I cant use re.send in a loop and res.JSON gives me the same result. My code below sends back the first user:
app.post('/rankcandidates', function(req, res){
var array = JSON.parse(req.body.array);
for (var i = 0;i<array[0].length;i++){
User.find({"_id" : { "$in" : [ array[0][i]._id] }
}).exec(function (err, result) {
res.setHeader('Content-Header', 'application/json');
res.send(JSON.stringify(result));
// also tried res.JSON but doesn't work
});
}
});
My Ajax call:
$.post("/rankcandidates",
{ array:JSON.stringify(array) },
function(data,status){
console.log(data); // comes out as a string of the first user
}
});
New Problem - Inserting objects into database with for loop:
app.post('/insertPositionIndex', function(req, res){
var array = JSON.parse(req.body.array);
console.log(array[0]); // data shown below
var ids;
var indexes;
for (var i=0;i<array.length;i++){
ids = array[i][0].map(function(element) { return element.position_id });
indexes = array[i][0].map(function(element) { return element.index_position });
console.log(ids);
console.log(indexes);
}
User.update(
{ "_id": req.user._id},
{
"$push":
{
"positionsApplied":{
position_id: ids,
index_position: indexes
}
}
}
).exec(function (err, result) {
res.json({ results: result });
});
});
One request can return only one response. In your case, you should first create array of user ids, and then query the user collection where you are searching all users whose id matches one element of that array. Here is a solution:
app.post('/rankcandidates', function(req, res){
var array = JSON.parse(req.body.array);
var ids = array[0].map(function(element) { return element._id })
User.find({"_id" : { "$in" : ids }})
.exec(function (err, results) {
res.json(results);
});
});