我有猫鼬这个模型
const WorkOrderSchema = new Schema({
title: {
type: String,
required: 'Enter a title for the order'
},
description: {
type: String,
required: 'Enter a description for the order'
},
deadline: {
type: Date,
required: 'Enter a deadline for the order'
},
workers: [{ type: Schema.Types.ObjectId, ref: "Worker" }]
});
WorkOrderSchema.path('workers').validate(function(workers) {
if(workers.length > 5){return false}
return true;
}, 'Too many workers');
module.exports = mongoose.model('Orders', WorkOrderSchema);
以及将工作人员分配给订单的此代码。
exports.assign_a_worker = function(req, res) {
Order.update({"_id": req.params.orderId},
{"$addToSet": {"workers": req.params.workerId}},
{runValidators: true},
function (err, order) {
if (err)
res.send(err);
res.json(order);
}
);
};
但是,它不能验证数组中工作程序的数量,并且允许我向模型中的workers数组添加无限个对象。不太确定出了什么问题。