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);
});
});