Parse.com - relation between table and Users table

84 Views Asked by At

I'm quite new on parse concepts, I have been always a classic relational database developer, sorry if I make basic mistakes.

The main idea is to develop a component that will allow a user to store some discount codes only assigned to him with a few basic properties (around 100).

By now, I have created a class called Codes and on the standard User's one, I have setup a new field called Codes with a relation to Codes object. I'm using Javascript SDK as it is going to be a mobile app.

First of all, is this data model the most suitable one to achieve my purpose or do you recommend me any other option?

On my first POC, I have created a simple application to register a user, create a Code and assign it to him but it is not working and I don't get any error message. Using parse WUI, I can see that User object is correctly created and also Code code but clicking on User's relation doesn't show any Code linked. Am I doing something wrong?

Here is my code

 success: function(user) {
    $scope.currentUser = user;

    var Code = Parse.Object.extend("Codes");
    var myCode = new Code();
    myCode.set("text", "This is a dummy test");
    myCode.save();

    var relation = user.relation("Codes");
    relation.add(myCode);
    user.save();
    $scope.$apply();
  }

Thanks in advance for your help

Regards

1

There are 1 best solutions below

1
On

First of all, is this data model the most suitable one to achieve my purpose or do you recommend me any other option? A: You're using a Relation model which is best for Many-To-Many relation. It should work perfectly for your use case. You can also use a Pointer model. That way you don't need to create anything on your User table but create a field of type "Pointer" on your Code table and point to User. You can name the field "owner" or anything like that. Pointer model is good for Many-To-One relation.

The problem with your code is that by the time you save code to the user, the code is not successfully created yet. As you know, javascript SDK is asynchronous, so user.save() would be called before myCode.save() gets completed. I think that's why you don't see the actual code in your Code table. You should use promise instead. Go ahead check the promise documentation on their website. For your reference, your code can be modified as below:

success: function(user) {
    $scope.currentUser = user;
    var Code = Parse.Object.extend("Codes");
    var myCode = new Code();
    myCode.set("text", "This is a dummy test");
    myCode.save().then(function(createdCode){
        var relation = user.relation("Codes");
        relation.add(createdCode);
        user.save();
        $scope.$apply();
    }, function(error){
        // handle error here.
    });
}