3

I'm using FeathersJS and MongoDB to develop an app. I want to prevent some services to create duplicates of some values (or pairs of values).

For example, the FeathersJS "Authenticate" service created with the feathers-cli tool doesn't prevent the app from creating 2 or more users with the same email (at least using MongoDB). Another example would be a service to create some "categories" for each user. I want that the backend prevents a user to create 2 or more categories with the same name, but I need to allow 2 different users to create their own categories although their names are the same (but not the users).

I know I can do this by using indexes in the MongoDB collections, but this would make the app MongoDB dependant.

Is there someone that knows if there's any kind of hook or whatever that is the recommended way to do such things "the FeathersJS way"?

Thank you!

Jordi Blanch
  • 187
  • 1
  • 11

1 Answers1

3

In most cases uniqueness can - and should - be insured at the database or ORM/ODM level since it will give you the best performance (something that in most cases isn't worth sacrificing for portability).

A more Feathers-y way and to accomplish more complex restrictions would be Feathers hooks which are an important part of Feathers and explained in detail in the basics guide.

In this case, a before hook could query the total of items and throw an error if there are any:

const { Conflict } = require('@feathersjs/errors');

app.service('myservice').hooks({
  before: {
    create: [async context => {
      const { fieldA, fieldB } = context.data;
      // Request a page with no data and extract `page.total`
      const { total } = await context.service.find({
        query: {
          fieldA,
          fieldB,
          $limit: 0
        }
      });

      if(total > 0) {
        throw new Conflict('Unique fields fieldA and fieldB already exist');
      }

      return context;
    }]
  }
})
Daff
  • 43,734
  • 9
  • 106
  • 120
  • Hello Daff, thank you for your answer. I'll continue using the MongoDB indexes for such purposes because of performance. – Jordi Blanch Sep 14 '18 at 07:35
  • @Daff Using database uniqueness system for performance is a good choice. However, how to properly handle the error and display the information the way we want? Using the errors hooks? – Soullivaneuh Feb 06 '21 at 17:13