简体   繁体   中英

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 });
        }
      });
    });

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.

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)
        }
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM