I am trying to insert the following data using sequelize and nodejs into my db
{
"basicDetails": {
"companyName": "demo",
"email": "demo5@demo.com",
"phone": "5019918819",
"address": "manab",
"pincode": "400078",
"city": "Mumbai",
"state": "Maharashtra"
},
"subOffices": [
{
"subofficename": "bpo",
"location": "random"
},
{
"subofficename": "fintech",
"location": "worli"
}
],
"companyUsers": [
{
"userName": "Random user",
"userEmail": "random@us.com",
"userPhone": "0000000000"
},
{
"userName": "Demo User",
"userEmail": "demo@us.com",
"userPhone": "1111111111"
}
]
}
I have basically 3 tables :-
basic details would be stored in a client table and using the id of that data. I would like to insert the sub offices and company users in there respective table where foreign key would be the id that I get from inserting my basic details into the client table
I am able to insert the basic details to the client table and fetch the id of that data . I would further like to do a bulk insert using sequelize including the id that I am getting from the client data as a foreign key to it.
router.post("/addClient", async function (req, res) {
const basicdetails = req.body.basicDetails;
console.log(basicdetails);
const subofficesData = [...req.body.subOffices];
const companyusers = [...req.body.companyUsers];
console.log("suboffices: " + suboffices);
subofficesData.forEach((item) => console.log(item));
companyusers.forEach((item) => console.log(item));
const data = await client.create({
companyName: basicdetails.companyName,
email: basicdetails.email,
mobileNumber: basicdetails.phone,
address: basicdetails.address,
pincode: basicdetails.pincode,
city: basicdetails.city,
state: basicdetails.state,
});
console.log(data.id);
const subofficesResult = await suboffices.bulkCreate(subofficesData, {
clientId: data.id,
});
console.log(subofficesResult);
// console.log(req.body.suboffices);
});
This doesn't actually look like a scenario where you want to use bulkCreate at all.
Look into utilizing the include property in the options object of your create method.
https://sequelize.org/master/manual/creating-with-associations.html