Search code examples
javascriptfeathersjs

Feathers-mongoose : Get by custom attribute in feathers-mongoose


I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const messages = new Schema({
    message: { type: String, required: true }
  }, {
    timestamps: true
  });

  return mongooseClient.model('messages', messages);
};

When the a user runs a GET command :

curl http://localhost:3030/messages/test

I have the following requirements

  1. This essentially tries to convert test to ObjectID. What i would like it to do is to run a query against the message attribute {message : "test"} , i am not sure how i can achieve this. There is not enough documentation for to understand to write or change this in the hooks. Can some one please help
  2. I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?

Thanks


Solution

  • In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is

    • In a before get hook, try to find the message by name
    • If it exists set context.result to what was found
    • Otherwise do nothing which will return the original get by id

    This is how it looks:

    async context => {
      const messages = context.service.find({
        ...context.params,
        query: {
          $limit: 1,
          name: context.id
        }
      });
    
      if (messages.total > 0) {
        context.result = messages.data[0];
      }
    
      return context;
    }
    

    How to create custom errors and set the error code is documented in the Errors API.