I have a problem when making a request to a MongoDB database in NodeJS using Mongoose.
What I am looking for is to make the request to the database (mongodb) and save the result in a variable. I have tried the following:
let a = Comment.find({idArticle:n._id.valueOf()});
console.log(a);
and it returns a huge object, but if I do the following:
Comment.find({idArticle:n._id.valueOf()},(err,r)=>{console.log(r.length);});
I see that it works in the console but of course it is not saved in a variable, so I tried the following:
let a = Comment.find({idArticle:n._id.valueOf()},(err,r)=>{ return r.length;});
console.log(a);
but nothing, it kept returning a huge object, I leave you the whole code
Article.find({},"_id title author").exec((err, article) => {
let template = [];
article.forEach(n => {
let a = Comment.find({idArticle:n._id.valueOf()},(err,r)=>{ return r.length;});
var d = new Date(n.date);
template.push({
title: n.title,
author: n.author,
date: `${d.getDate()}/${d.getMonth()}/${d.getFullYear()}`,
id: n._id,
comments: a
});
});
role= getRole(req);
res.render("adminArticulos",{
session: role.user,
json: template
});
});
I also tried to do the following:
Comment.find({idArticle:n._id.valueOf()},(err,r)=>{
var d = new Date(n.date);
template.push({
title: n.title,
author: n.author,
date: `${d.getDate()}/${d.getMonth()}/${d.getFullYear()}`,
id: n._id,
comments: r.length
});
});
but when i did the render
res.render("adminArticulos",{
session: role.user,
json: template
});
the template variable passes empty.
The problem you have is due to asynchrony.
On the line
let a = Comment.find({idArticle:n._id.valueOf()},(err,r)=>{ return r.length;});
you think it's synchronous and it's not, since MongoDb's database queries are asynchronous, so it will return an unresolved promise (that famous huge object you comment on in your query).As a solution, I show you several solutions, one with your code, another using
async/await
and the last one using the methodaggregate
, so you can see several alternative solutions that can help you think of the best path for your platform.async/await
:aggregate
with the stages to perform the MongoDB query:I leave you documentation about
aggregate
MongoDBAny questions, do not hesitate to ask to help you.
I hope this code will help you.
All the best