How do you seed a mongodb database such that the Keystone 5 CMS recognizes the many-to-many relationships?
I figured out a solution. Here's the background:
When I define the schema, Keystone creates corresponding MongoDB collections. If there is a many-to-many relationship between object A and object B, Keystone will create 3 collections: A, B, and A_relationshipToB_B_relationshipToA.
That 3rd collection is the interface between the two. It's just a collection with pairs of ids from A and B.
Hence, in order to seed my database with a many-to-many relationship that shows up in the Keystone CMS, I have to seed not only A and B, but also the 3rd collection: A_relationshipToB_B_relationshipToA.
Hence, seed-data/index.ts
will have some code that inserts into that table:
...for (const seller of sellers) { const sellerToAdd = { name: seller.name }; const { _id } = await mongoose.model("Seller").create(sellerToAdd); // Product_sellers_Seller_products Insertion for (const productId of seller.products) { await mongoose .model("Product_sellers_Seller_products") .create({ Product_left_id: productIds[productId], // (data.ts id) --> (Mongo ID) Seller_right_id: _id, }); } }...