我需要在插入mongodb集合时验证文档。 我有预约应用程序。 如果我已经在今天的日期收集了'paciente',我想再次拒绝将此“paciente”添加到该系列中。
我已经创建了下一个验证,但是尽管我的代码找到了正确的“paciente”已经收集,我仍然可以包含它。
我做错了什么?
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);
});
});