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

Advertisements

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

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

Leave a ReplyCancel reply