Codz Boltz
Codz Boltz

Reputation: 1

Node js , mongo DB get data from multiple collections using async

Hello im trying to get all my blogs from DB and change the author name from another collection from the database then rendering them to ejs file however the page renders before the array is filled up

app.get('/', async (req, res) => {
      let blogList = new Array(); 
      await Blog.find({}, function (err, foundBlog) { 
        console.log(foundBlog);
        if (err) {
          console.log(err);
        } else {
          foundBlog.forEach(async (blog) => {
            await Author.findById(blog.author, async (err, author) => {
              if (err) {
                console.log(err);
              } else {
                blog.author = author.name;
                console.log('this is the blogs' + blog);
                blogList.push(blog);
                console.log('array length 1 is ' + blogList.length);
              }
            });
          });
          console.log('array length 2 is ' + blogList.length);
          console.log(blogList);
          res.render('home', { blogs: blogList });
        }
      });
    });

Upvotes: 0

Views: 316

Answers (2)

RONAK SUTARIYA
RONAK SUTARIYA

Reputation: 544

for your query, you can explore populate in your Mongo Schema in the collection.

const BlogSchema = new mongoose.Schema({
 author:{
  type:ObjectId,
  ref:"Author" //here it is model name 
 }
})
const Blog = mongoose.model("Blog", BlogSchema )

const AutherSchema = new mongoose.Schema({
 _id:{
  type:ObjectId
 }
})
const Auther = mongoose.model("Auther", AutherSchema)

 app.get('/', async (req, res) => {
      
 const blogs = await Blog.find({}).populate('author').exec(); // field name author is being populated.
         res.send(blogs)
        }
    )

Upvotes: 0

Asad Haroon
Asad Haroon

Reputation: 492

Please use ref of Author in Blog. In other words make a relation of blog with author. And then your backend should be as follows:

app.get('/', async (req, res) => {
      
         const blogs=await Blog.find({}).populate('author').exec(); // field name author is being populated.
      
          res.render('home', { blogs });
        }
    
    );

const BlogSchema=new mongoose.Schema({
 ... rest of fields,
 author:{
  type:ObjectId,
  ref:"Author" // here it is model name 
 }
});

With this code now your whole author object will be embedded in each blog like:

blog={
  name:"",
  author:{
    name:"Abc",
  }
}

And you can easily get author details by accessing blog.author.name.

Upvotes: 1

Related Questions