我有一个Express端点执行以下操作:
router.put('/:appointmentId', async (req, res) => {
try {
let appointment = await Appointment.findOneAndUpdate(
{ _id: req.params.appointmentId },
{
member_id: req.body.appointment.memberId,
client_id: req.body.appointment.clientId,
address_id: req.body.appointment.addressId,
unit_id: req.body.appointment.unitId,
dateAndTime: req.body.appointment.dateAndTime
},
{
new: true,
runValidators: true,
context: 'query'
}
);
res.send(appointment);
} catch (err) {
res.send(err);
}
});
约会是一种猫鼬模型。此模型具有以下路径验证之一:
AppointmentSchema.path("unit_id").validate(async function (unit_id) {
let unit = await Unit.findById(unit_id);
if ((unit === null) || !unit.address_id.equals(this.address_id)) {
return false;
}
return true;
}, "unit_id is not valid");
Appointment架构如下所示:
var AppointmentSchema = new mongoose.Schema(
{
member_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Member',
required: true
},
client_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Client',
required: true
},
address_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Address',
required: true
},
unit_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Unit',
required: true
},
dateAndTime: {
type: Date,
required: true
}
}
);
当我点击Express端点时,this.address_id
未定义且我的验证无法正常工作。我的理解是,如果我将runValidators
设置为true
并context
设置为'query'
,我就可以获得此访问权限。
我做错了什么?
作为旁注,我还注意到Express在验证失败时返回200
状态。这很奇怪。
感谢。