Search code examples
loopbackjs

How to set relation foreign key to be required


I have two models. Company and Booking.
In the relation part of model Company

"bookings": {
  "type": "hasMany",
  "model": "Booking",
  "foreignKey": "companyId"
}

The issue is, it is possible to post a Booking without companyId which is not ok.
From the explorer.

Booking {
  bookingId (string, optional),
  name (string),
  location (string),
  companyId (string, optional)
}

Solution

  • You actually can't enforce this particular validation out-of-the-box. Instead you have a couple different options:

    a) You can enforce the creation of Booking through company through the endpoint, POST /api/Company/{id}/Bookings by disabling Booking.disableRemoteMethod('create', ...) along with any other methods that have the ability to create records from the Booking model.

    b) You can add a remote hook to check whether or not the company record exists and throw an error accordingly.

    Booking.beforeRemote('create', function(ctx, booking, next) {
      var Company = Booking.app.models.Company;
      var companyId = ctx.req.body.companyId;
    
      if (companyId) {
        errorMsg = 'Company with id=' + companyId + ' does not exist.';
        var noCompany = new Error(errorMsg);
        Company.findById(companyId, function(err, company) {
          if (err) next(err);
          if (!company) {
            ctx.res.statusCode = 400;
            next(noCompany);
          } else {
            next();
          }
        });
      } else {
        next();
      }
    });
    

    You will also have to do the same thing for any other endpoints that allow record create such as PUT /api/Bookings.

    Hope that helps!