0

I'm doing a project using Express, & Sequelize and have run into an issue:

I'm trying to create an api route that, on a button click, will create a row in my 'member' & 'memberinstrument' tables. Those tables have an association in my models that: member 'hasMany' memberinstruments & memberinstruments 'belongsTo' member.

This is what I have right now:

router.post("/api/individual/signup", async (req, res) => {
    try {
        const member = await db.Member.create({
            memberName: req.body.memberName,
            location: `${req.body.city}, ${req.body.state}`,
            profilePicture: req.body.profilePicture,
            UserId: req.user.id
        })
        const memberInstrument = await db.MemberInstrument.create({
            instrument: req.body.instrument,
            MemberId: member.id
        });
        res.json({ member, memberInstrument });
    } catch (error) {
        console.log(error.message);
        res.status(500).send('Sever Error');
    }
})

I'm testing it out in postman and it simply says I have a 'server error' (which doesn't happen if I delete the whole memberInstrument posting section) and in node I get "Cannot read property 'id' of undefined". I know it must have something to do with the timing of trying to create member, and then trying to get that member id for memberinstrument, but I can't figure out how to resolve this.

Any help would be much appreciated!

(edit: I commented out both UserId & MemberId and it successfully posts.

uncommenting just UserId creates the same error: UserId is a nullable field so I don't know why it's doing a server error if I don't define it (or maybe I have to define it as null but I do not know how to do that in postman since it's coming from .user instead of .body

uncommenting just MemberId creates the same error)

2 Answers2

0

Since I'm doing this in Postman, and don't know how to send a req.body with that, I was getting that id error. I changed req.user.id to req.body.id which will be populated with information from a front end state and it is now working correctly.

0

I think it's unnecessary for you to include all the fields in your .create()

try this

router.post("/api/individual/signup", async (req, res) => {
try {
  const data = req.body;
  const member = await db.Member.create(data);
  const [registration, created] = member;
  if(created){
    //insert more of your code here on creating **MemberInstrument**, this is just a sample.
         await db.MemberInstrument.create(registration.member_id);
  }
  res.json({
    registration,
    created
  });

 } catch (error) {
  console.log(error);
  res.status(500);
  }
}

On your postman request, you will input the body or fields in json format, except the ID, IDs should not be included on the postman body.

John Carlo
  • 54
  • 2
  • 13