Search code examples
node.jsloopbackjsloopback

Loopback FindById returns null, not error when searching with a wrong Id


I am struggling with the findById function of Loopback. When executing the function below with a non existing/wrong ID it returns an empty object/null and statuscode 200, not an error. When using the findById method in Loopback's explorer I receive an error message and 404 statuscode, as expected.

Can this be a bug inside Loopback? I can't imagine that I'll have to check if the result is empty every time. It should trow an error right?

Specs

  • Loopback 3.18.1
  • Mlab mongo db
  • Node version 8.9.1

Loopback function inside a Models js file

Model.add = function(data, cb) {
let Vehicle = app.models.Vehicle;
Vehicle.findById('5b33a528b959503aeabf4827', function(err, vehicle) {
  if (err) {
    console.log(err);
  };
  cb(null, vehicle);
});
};

Solution

  • From the docs:

    PersistedModel.findById(id, [filter], callback)

    And for parameter callback the return instance is:

    Model instance matching the specified ID or null if no instance matches.

    https://apidocs.loopback.io/loopback/#persistedmodel-findbyid