Reputation: 2844
Let's say I have a model user, which can have multiple houses. These houses can have multiple parking spots, which then can have multiple cars or bikes
Users > Houses > Parking spots > [cars, bikes]
How can I check if a car is related to a user?
Let's say, for example, that when a user (currently logged in user) wants to edit or delete a car, I'd like to check if he is the owner of that car. Same goes for when he wants to perform an action on a house or a parking spot.
Since the model user is not directly associated with the model car or parking spots, what's the best way to check if the objects are related to the user? Is there any way to look up the 'first-level association'?
Thanks in advance
Dennis
Upvotes: 1
Views: 67
Reputation: 3993
I guess you defined all these one-to-many relations in your models.
Then you have everything to find the user related to a car:
Here is a simple example using callbacks:
Car.findOne({id: 1}).exec(function(err, car) {
Parking.findOne({id: car.parking}).exec(function(err, parking) {
House.findOne({id: parking.house}).exec(function(err, house) {
res.json(house.user); // <= returns the user id
});
});
});
To reduce the number of calls, you can use the populate()
method:
Car.findOne({id: 1}).populate('parking').exec(function(err, car) {
House.findOne({id: car.parking.house}).populate('user').exec(function(err, house) {
res.json(house.user); // returns the user object
});
});
You could also use the promise API to organize your asynchronous code differently.
Upvotes: 1
Reputation: 71
If the cars or bikes only can be owned by a single user you could always add an userID association model in your cars and work your way from there, or else you could do a hard SQL query with a lot of subqueries for example:
"SELECT car.name, car.id, car.parkingspot FROM cars, parkingspots, houses, users WHERE
car.parkingspotID = parkingspot.ID
AND
parkingspot.houseID = house.ID
AND
house.userID = MY_USERID
"
Upvotes: 1