Creating Database Records in Redux
In the previous lessons we prepared everything to fill our database with data. Let's get started.
Let's open our product app, and in it the file server.js
. First, we'll decide how many and what kind of data objects we need. We have 4
sellers, let's say each of them has 3
products. Let's enter two constants for this right after the import lines:
const NUM_SELLERS = 4
const PRODS_PER_SELLER = 3
Now at the end of the file, before exporting the worker, we'll make a for loop in which we'll use create
to create database entries for our 4
sellers:
for (let i = 0; i < NUM_SELLERS; i++) {
const newSeller = db.seller.create(createSellerData(i))
}
For each seller we have 3
products, so in the seller loop we will make another nested for, in which we will create records for products:
for (let i = 0; i < NUM_SELLERS; i++) {
const newSeller = db.seller.create(createSellerData(i))
for (let j = 0; j < PRODS_PER_SELLER; j++) {
const newProduct = createProductData(newSeller)
db.product.create(newProduct)
}
}
Great! This completes our work with the database.
We only have one more thing to do. We need the seller's id to be passed to the seller
field of the product object. Let's write another function serializeProduct
below after the for loops, in which we will add this id:
const serializeProduct = (product) => ({
...product,
seller: product.seller.id,
})
Open your application with students. Let's say you have three teachers, and each of them has 3
students. After reading this lesson, use the for
loop to create 3
teacher records in the database.
Next, make a second for
loop inside the loop from the previous problem, which creates 3
students.
After the nested for
loops, write a serializeStudent
function as shown in the tutorial, which will populate the teacher
field with the teacher's id.