I have a problem when I want to display a list of data from Mongoose (MongoDB) to my front-end in ejs
For example:
var User = require("./models/user");
var Houses = require("./models/house");
app.get("/", function(req, res){
var list_houses = [];
for(var i=0; i<req.user.city.length; i++)
{
Houses.find({'city': req.user.city[i]}, function(err, result){
if(err)console.log(err);
if(result){
list_houses = list_houses.concat(result);//add array result to array list_prices
}
});
}
res.render("/prices_houses",{list_houses: list_houses});
});
I found the module 'async', but neither does not work, my code was:
var User = require("./models/user");
var Houses = require("./models/house");
var async = require('async');
app.get("/", function(req,res){
var list_houses = [];
async.waterfall([
async.each(req.user.city, function(result, callback){
Houses.find({'city': result}, function(err, result){
if(err)console.log(err);
if(result){
list_houses = list_houses.concat(result);
}
});
});
], function(arg1, callback){
res.render("/prices_houses", {list_houses: list_houses});
});
});
When I want to display 'list_houses.length' in ejs, it shows this: 0
<%=list_houses.length%>
My schemas in mongoose are:
var User = new mongoose.Schema({
city : [String]
...
});
var House = new mongoose.Schema({
city: String
price: Double
});
I know that the problem is with Asynchronous, but I don't know how to solve it. Please help me with this problem.