0

I need validate an document when inserting into mongodb collection. I have an appointment app. If I already have a 'paciente' included into collection with today date, I´d like to reject the addition of this "paciente" again into the collection.

I have created the next validation , but despite my code find correctly the "paciente" already is into collection, I still can include it.

What am I doing wrong?

var mongoose=require('mongoose');
var FilaSchema = new mongoose.Schema({
  profissional: {type:mongoose.Schema.Types.ObjectId , ref:'Profissional'},
  paciente: {type:mongoose.Schema.Types.ObjectId , ref:'Cliente'},
  especialidade:{type:mongoose.Schema.Types.ObjectId, ref:'CboMedico'},
  convenio:{type:mongoose.Schema.Types.ObjectId , ref:'Convenio'},
  datahora_ent:{type:Date, required:true},
  datahora_sai:{type:Date},
});

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

FilaSchema.path('paciente').validate(function (value) {
  var self = this;
  var today = new Date();
  var di = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
  var df = addDays(di,1);
  return mongoose.models.Fila.find( { 
    '_id': { $ne: self._id },
    'paciente':self.paciente,
    'datahora_ent': { $lt: df, $gte: di } 
  }, function (err, appointments) {
    var ok=(! appointments || appointments.length === 0);
    //ok is false when "paciente" already exists in collection
     return ok;
  });
},"Paciente já está na fila"); 

////router to create
router.post('/',function(req,res,next){ 
    var item = new  Fila(req.body);  
    item.save( (err, createdObj) => {  
        return res.send(createdObj);
    });
});
Luiz Alves
  • 2,575
  • 4
  • 34
  • 75
  • http://mongoosejs.com/docs/validation.html#async-custom-validators. As well as :"you cannot return a value from an asynchronous call" like that. Supply a callback. – Neil Lunn Oct 20 '17 at 11:55
  • Thank you Mr Neil. I put the callback into the function but now I get an warning:"DeprecationWarning: Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. " How can I get rid off it? – Luiz Alves Oct 20 '17 at 12:06
  • That would be a another question then. Perhaps you should search for an answer, and then post as a separate question if you cannot find the answer. You probably should start by reading that linked page in the comment above a little more carefully though. Hint, "implicit" means you forgot to "explicitly" specificity something. Without looking at the page there is a particular stand out option that comes to mind and I know they use it in the code example. – Neil Lunn Oct 20 '17 at 12:08
  • OLk, thank you very much – Luiz Alves Oct 20 '17 at 12:16

0 Answers0