User has many Shopping Lists
A User has many Shopping Lists, to create a has-many relation between User and Shopping List model, we will need to do a similar exercise like we did for Shopping List and Item model. Each ShoppingList
object would need to keep an ID to the user it belongs to so that we can query for all Shopping Lists for that user. To add this, we will need to follow these steps:
- Open the
ShoppingList.swift
file in your Vapor app and add the following new property as an instance variable inside theShoppingList
class to storeuserId
:
var userId: Identifier
- Next, create a user-computed property, which will allow us to get the user to a Shopping List:
var user: Parent<ShoppingList, User> { return parent(id: userId) }
- Now, add the
userId
column name that will be used by MongoDB to store the user ID inside of the database collection:
static let userId = "user__id"
- Now, we will need to update our initializer so that it can take the
userId
as a parameter and assign it to itsuserId...