Search code examples
node.jsmongodbvalidationmongoosefeathersjs

How to prevent changes from services


I'm using Feathers.js with Mongoose and I want to create a field that cannot be changed by the services.

// account-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
require('mongoose-type-email');

module.exports = function(app) {
  const mongooseClient = app.get('mongooseClient');

  const recovery = new mongooseClient.Schema({
    token: { type: String, required: true }
  }, {
    timestamps: true
  });

  const account = new mongooseClient.Schema({
    firstName: { type: String, required: true },
    surname: { type: String, require: true },
    phone: { type: String, require: true },
    email: { type: mongoose.SchemaTypes.Email, required: true, unique: true },
    birth: { type: Date, required: true },
    gender: { type: String, required: true },
    country: { type: String, required: true },
    address: { type: String, required: true },
    address2: { type: String, required: false },
    city: { type: String, required: true },
    postcode: { type: String, required: true },
    password: { type: String, required: true },
    status: { type: String, required true }
  }, {
    timestamps: true
  });

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

No one can make a post at /account/<id> and change the field status. This field should only be changed when internally. When some approval service request.

How can I implement this behavior?


Solution

  • This is a perfect use case for Feathers hooks. When accessed externally, in a service method call params.provider will be set so you can check for it and remove the field from data if it is:

    module.exports = function() {
      return async context => {
        if(context.params.provider) {
          delete context.data.status;
        }
      }
    }
    

    This hook will be a before hook for the create, update and patch method.