Reputation: 480
I'm having issues making n-n relationships work in Thinky:
Here is the code that defines the model:
module.exports = function(thinky){
var User = thinky.createModel("User",{
SNIP: A Bunch of properties
});
User.hasAndBelongsToMany(User,"friends","id","id");
return User;
}
And here is the route where a friend is added.:
router.route('/user/:user_id/addFriend')
.post(function(req,res){
User.get(req.params.user_id).run().then(function(user){
User.get(req.body.id).run().then(function(friend){
if(!user.friends){
user.friends = [friend];
}else{
user.friends.push(friend);
}
user.saveAll().then(function(result){
res.json({user:result});
});
});
},function(err){
console.log(err);
res.status(400).json({error:err});
});
});
The result returned on the addFriend route has the friend, but when I retrieve the users later, the relationship is nowhere to be seen. If I look in RethinkDB Data Explorer thinky has created the User_User table for the relationship, and the following data is in it:
[
{
"id": "8f08de10-6f3c-486e-958a-cb0e05b79244_de484182-5aab-4773-a374-e0ba292f7f80" ,
"id_id": [
"de484182-5aab-4773-a374-e0ba292f7f80" ,
"8f08de10-6f3c-486e-958a-cb0e05b79244"
]
}
]
But Thinky refuses to see the relationship as existing. What am I doing wrong?
Upvotes: 2
Views: 896
Reputation: 4353
Because a user is linked to another user, you could have a circular reference (user1 is friend with user1). In this case to avoid error like Maximum stack size exceeded, thinky does not keep recursing and requires you to manually specify what you want to save.
This should work:
user.saveAll({friends: true}).then(function(result){
res.json({user:result});
});
Upvotes: 3