【发布时间】:2014-09-11 10:54:03
【问题描述】:
我有一个带有 Meeting 和 Participants 数组的基本 Mongoose 模型:
var MeetingSchema = new Schema({
description: {
type: String
},
maxNumberOfParticipants: {
type: Number
},
participants: [ {
type: Schema.ObjectId,
ref: 'User'
} ]
});
假设我想验证添加的参与者数量不超过该会议的 maxNumberOfParticipants。
我已经考虑了几个选项:
- 自定义验证器 - 我不能这样做,因为我必须针对另一个 (maxNumberOfParticipants) 验证一个属性(参与者长度)。
- 中间件 - 即预保存。我也不能这样做,因为我通过 findOneAndUpdate 添加参与者(除非我使用 save,否则不会调用这些参与者)。
- 添加验证作为我的 addParticipants 方法的一部分。这似乎是合理的,但我不确定如何从模型中传回验证错误。
请注意,我不想在控制器(express、MEAN.js 堆栈)中实现验证,因为我想在模型上保留所有逻辑和验证。
这是我的 addParticipants 方法:
MeetingSchema.methods.addParticipant = function addParticipant(params, callback) {
var Meeting = mongoose.model('Meeting');
if (this.participants.length == this.maxNumberOfParticipants) {
// since we already have the max length then don't add one more
return ????
}
return Meeting.findOneAndUpdate({ _id: this.id },
{ $addToSet: { participants: params.id } },
{new: true})
.populate('participants', 'displayName')
.exec(callback);
};
不确定在这种情况下如何返回验证错误,或者即使这种模式是推荐的方法。
【问题讨论】:
-
在我的好朋友 digger69 的帮助下,我想要回传一个错误:callback({errors: [{message: 'Too many members'}]});这在我们使用的 mean.js(样板文件)的上下文中有效,似乎是一个很好的答案,但我很好奇这是否仍然是正确的方法。
标签: node.js mongodb validation mongoose mean-stack