Reputation: 194
Im using MongoDB database for tasks and im trying to find all the tasks with task_rating : "OK" and get the result into one list and all tasks with task rating: "NOK" to second list and finaly render it to my HTML as two lists of information.
The problem is that whene I want to return the find results as list to outside value, it always returns me a weird object of Mongoose.
my code:
app.get("/", function(req, res) {
var nok_l = tasks.find({ task_rating: "NOK" }, (err, nokTasks) => {
if (err)
console.log(err);
else {
return nokTasks;
}
});
var ok_l = tasks.find({ task_rating: "OK" }, (err, okTasks) => {
if (err)
console.log(err);
else {
return okTasks;
}
});
console.log(ok_l);
res.render("tasks", {
ok_l: ok_l,
nok_l: nok_l
});
});
the result of the console.log print is werid object of Mongoose and not my list.
Thank you.
Upvotes: 0
Views: 261
Reputation: 4783
The problem is that you're printing the Mongoose's promise object, not the returned data, since the Mongoose#find is assync.
There are many ways to handle over this scenario, but the most basic and "didactic" is return the data only when the promise is resolved:
app.get("/", function(req, res) {
tasks.find({task_rating: "NOK"}, (err, nokTasks) => {
if (!err) {
tasks.find({task_rating: "OK"}, (err, okTasks) => {
if (!err) {
res.render("tasks", {
ok_l: okTasks,
nok_l: nokTasks
});
}
});
}
});
});
But, this stack can be better structured if we store the promises references and resolve all using Promise#all:
app.get("/", function(req, res) {
let promises = [];
promises.push(tasks.find({task_rating: "NOK"}).exec());
promises.push(tasks.find({task_rating: "OK"}).exec());
Promise.all(promises).then( (allTasks) => {
// here it's necessary to handle the "OK" and "NOK" lists
res.render("tasks", {
list: allTasks
});
});
});
Upvotes: 1