Search code examples
stronglooploopbackjs

mongodb belongsTo Foreign key is null


So this question feels a lot like my last one. Strongloop is making me feel like such a noob. lol.

I stole this from some of the LB examples:

var Order = mongoDev.createModel('order', {
    customerId: Number,
    orderDesc: String
});

var Customer = mongoDev.createModel('customer', {
    id: {type: Number, id: true},
    name: String,
    emails: [String],
    age: Number},
  {strcit: true});

//Order.belongsTo(Customer);
Order.belongsTo(Customer, {as: 'customer', foreignKey: 'customerId'});
Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'});

In the explorer I see both the customer & order endpoints. Also customers has endpoints for /customers/{id}/orders and orders has /orders/{id}/customer etc. So far so good.

I have this customer added:

GET .../api/customers/53c599594e23e50000a41acf
{
  "id": "53c599594e23e50000a41acf",
  "name": "John1",
  "emails": [
    "[email protected]",
    "[email protected]"
  ],
  "age": 30
}

When I post an order I get a null customerId:

POST .../api/customers/53c599594e23e50000a41acf/orders
    data: {"orderDesc": "whatever"}

result:
{
  "customerId": null,
  "orderDesc": "whatever",
  "id": "53c59d1efd31a4000062e7d8"
}

Any ideas what I'm doing wrong here?


Solution

  • Okay, solved this. The examples I stole from had the Id's typed as Numbers. Changing those to Strings fixed this problem for me.

    var Order = mongoDev.createModel('order', {
        customerId: String,
        orderDesc: String
    });
    
    var Customer = mongoDev.createModel('customer', {
        id: {type: String, id: true},
        name: String,
        emails: [String],
        age: Number},
      {strcit: true});