Thursday, 13 April 2017

MongoDB Dinamically validate field in update

I want to know if is possible validate the request from a form before update a record in MongoDB.

Model:

const mongoose = require('mongoose');
const Schema =  mongoose.Schema;

const batchSchema = Schema({
  batch_number:{type: String, required: true},
  work_order_id:{ type: Schema.Types.ObjectId, ref: 'work_orders' ,required: true},
  start_date_time:{type: Date, required: true},
  end_date_time:{type: Date},
  status:{type: String},
  //create_date:{type: Date, default: Date.now}
},
{
  timestamps: true
});

const Batch = module.exports = mongoose.model('batches',batchSchema);

My Controller:

const mongoose = require("mongoose");
const Batch = require('../../models/production/batch');
const batchController = {};

batchController.index = (callback, limit) => {
  Batch.find(callback).limit(limit)
                      .lean(true)
                      .populate('work_order_id');
};

batchController.show = (id, callback) => {
  var query = {_id: id};
  Batch.findById(query,callback)
        .lean(true)
        .populate('work_order_id');
}

batchController.insert = (batch, callback) => {
  Batch.create(batch,callback);
}

batchController.update = (id, batch, options, callback) => {
  var query = {_id: id};
  var update = batch;
  Batch.findOneAndUpdate(query, update, options, callback);
}

batchController.remove = (id, callback) => {
  var query = {_id: id};
  Batch.remove(query, callback);
}

module.exports = batchController;

My Route (Only for update):

  app.put('/api/batches/:_id',(req, res) => {
      var id = req.params._id;
      var batch = req.body;
      Batch.update(id, batch,{}, (err, batch) => {
        if (err){
          res.status(500).json({msg:"Error en aplicacion",err});
        }
         res.status(200).json(batch);
      });
  });

In the create method the model validate the fields, but in the update, mongoose or mongodb doesn't valdiate the data.

I don't know if this an error I made in the definition of the model or the controller or this is the normal behavior from mongodb and mongoose.

for the create method I create function to validate the fields:

function validation(data){
  let errors = {};

  if (!data.batch_number) errors.batch_number = "No puede ser nulo";
  if (!data.work_order_id) errors.work_order_id = "No puede ser nulo";
  if (!data.start_date_time) errors.start_date_time = "No puede ser nulo";
  if (!data.status) errors.status = "No puede ser nulo";

  if (data.batch_number === '') errors.batch_number = "No puede ser vacio";
  if (data.work_order_id === '') errors.work_order_id = "No puede ser vacio";
  if (data.start_date_time === '') errors.start_date_time = "No puede ser vacio";
  if (data.status === '') errors.status = "No puede ser vacio";

  const isValid = Object.keys(errors).length === 0;
  return {errors, isValid}
}

This function works fine in the create, but in the update I want o save only the fields sended in the request, not all the fields.

I don't want to harcode the validation for the update.

I was reading in the version 4.0 of mongodb there is an option runvalidators. and this option do the validations I need.

I can only use stable version (client requeriment), I am using Mongodbd 3.4.2 and mongoose 4.8.3.

there is a way to dinamically validate the field sended in the request body in a update method in mongodb with mongoose.

Thanks in advance.



via joselegit

No comments:

Post a Comment