Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute find all method after executing for loop in Sequelize Node.Js?

I have a for loop. And I inserted each value into a table. After that when I query using findAll/findOne method, it says null. I want to get the data of User_Paper table after executing for loop.

const newPaper = new Paper({
                    title,
                    abstract,
                    contributor,
                    contributor: authors,
                    paper_file: file,
                    paper_topicId: ptopic.id,
                    categoryId: c1.id,
                    postingDate,
                    postingTime
                  });
                  newPaper.save().then(new_paper=> {
               
                    for (let i = 0; i < new_paper.contributor.length; i++) {
                      const newUser_Paper = new User_Paper({
                        userId: null,
                        username: new_paper.contributor[i],
                        paperId: new_paper.id,
                      });

                      newUser_Paper.save()
                     
                     }
                     User_paper.findOne({
                       where: {
                          username: : Touhid,
                          paperId: new_paper.paperId
                       }
                     }).then(x=>{
                         console.log(x)
                     })
                    })

After that the output is showing null. I want to get the data of User_Paper table after executing for loop.

This is my two table. Please Help me out.
PaperUser_Paper

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason why you are getting null is that you are not waiting for the save of the User_Paper objects that you are creating in the for loop. You need to call save() on each of those objects before you can query for them.

newUser_Paper.save().then(() => {
      // Now you can query for the User_Paper objects
      User_paper.findOne({
        where: {
          username: :Touhid,
          paperId: new_paper.paperId
        }
      }).then(x => {
        console.log(x);
      });
    });
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading