Skip to content

HasMany Relationship Storing same id for foreign key and primary key #151

Closed

Description

@britztopher

When you have a hasMany relationship, say 1 User can have many Orders, and you use the function for adding a new order for this user. I am getting a weird occurrence where the FK(userId) for the user in the Orders collection is the exact same as the PK in the Orders table.

For example, when I use this method:

User.order.create({id: User.getCurrentId(), order: order}).$promise
              .then(function (order) {
                $log.debug('updated order on backend to: ', order);
              },
              function (reason) {
                console.log('cant update order because: ', reason);
              });

which is created with angular SDK. The result in the database is

db.orders.find().pretty()
{
    "_id" : ObjectId("5566254bf7e604876c9e042f"),
    "userId" : ObjectId("5566254bf7e604876c9e042f"),
...

As one can see both the Foreign Key(userId) and the Primary Key(_id) are exactly the same. The problem here is that, when I want to create another Order for the same customer I get a "duplicate key" error because the PK is the same again.

Whats even more interesting when I use the swagger interface and generate the REST call manually using:

POST /users/{id}/orders

I get different PKs and FKs. Dont know whats going on here, but I dont think its the model declaration in my json files on node because swagger is doing this correctly.

Activity

  1. bajtos commented on Jun 1, 2015

    @bajtos
    Member

    I am afraid you are using the API incorrectly. Here is the correct way how to create a related instance:

    User.order.create({id: User.getCurrentId()}, order).$promise
                  .then(function (order) {
                    $log.debug('updated order on backend to: ', order);
                  },
                  function (reason) {
                    console.log('cant update order because: ', reason);
                  });

    See this unit-test and the API docs generated in your services files for more information. Alternatively, take a look at User.accessTokens.create docs, it is using the same HasMany relationship.

  2. britztopher commented on Jun 1, 2015

    @britztopher
    Author

    Thanks @bajtos, sorry for the misread in docs, as I thought the params and the payload had to be within the same object.

  3. bajtos commented on Jun 1, 2015

    @bajtos
    Member

    No worries, I was glad to help :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions