'Retrieve two foreign keys nodejs sequelize
I have a route and I want it to send two primary keys as foreign keys to my orderline table. I have three tables a customer, address and orderline table. an orderline has one customer and one address as foreign keys. I´m really struggling to figure it out. My route looks like this:
import express from "express";
import expressAsyncHandler from 'express-async-handler';
import { isAuth } from '../utlis';
import {Orderline, Address} from '../models';
const orderRouter = express.Router();
orderRouter.post(
'/',
isAuth,
expressAsyncHandler(async (req, res) => {
const customerId = req.customer.id;
const addresss = Address.findOne({where: {CustomerId: customerId}})
const addressId = addresss.id
const createdOrder = ({
totalPrice: req.body.totalPrice,
itemsPrice: req.body.itemsPrice,
taxPrice: req.body.taxPrice,
shippingPrice: req.body.shippingPrice,
AddressId: addressId,
CustomerId: customerId
});
Orderline.create(createdOrder);
res.status(201).send({ message: 'New Order Created', data: createdOrder});
})
);
export default orderRouter;
As seen in the code I have attempted to retrieve the address that has the id of the user logged in and then gett the ID and send that as the value. I would ideally like to find the postcode,address and customerID in the address table and Any help/guidance is much appreciated.
Solution 1:[1]
First, you need to indicate await
to the left from 'findOne' and create
because they are async functions and you want to get the result in the calling code:
const customerId = req.customer.id;
const address = req.address;
const postcode = req.postcode;
const addresss = await Address.findOne({
where: {
CustomerId: customerId,
address: address,
postcode: postcode
}
})
const addressId = addresss.id
const createdOrder = ({
totalPrice: req.body.totalPrice,
itemsPrice: req.body.itemsPrice,
taxPrice: req.body.taxPrice,
shippingPrice: req.body.shippingPrice,
AddressId: addressId,
CustomerId: customerId
});
const newOrder = await Orderline.create(createdOrder);
// in case you want to send the whole orderline object along with its generated ID
res.status(201).send({ message: 'New Order Created', data: newOrder});
And if you don't indicate attributes
option in findOne
you will get all attributes of Address
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |