Reputation: 2049
Im trying to setup my MongoDB design in such a way that there is a projects
collection, and a people
collection. The Project
model schema contains a _people
item, which references the People
model. (As opposed to the People model having a field to reference the project he/she belongs to. It needs to be like this)
I need to run a validation whenever a new document is created in the people
container, that there can be only one manager per a project. This would be very easy if it was possible for me to execute a query for the elements validation in the schema, but I don't believe thats possible...
Heres the schema for the People
model currently:
const peopleSchema = new Schema( {
name: {
type: Schema.Types.String,
required: true,
minlength: 3,
maxlength: 25,
trim: true,
select: true
},
isManager: {
type: Schema.Types.Boolean,
default: false,
validate: {
validator: function ( v ) {
// How can I check if there are any existing `people` documents with the
// `isManager` set to true, which are referenced by the same project.
// If I can return a promise from here, then I can just execute a query and verify the results
},
message: 'There can be only one manager per each group'
}
}
})
As you can see in the isManager.validate.validator
function, I noted that if this documents isManager
is set to true, I need to find a way to check that there isn't already a person
document referenced by the same project that is also a manager.
Knowing which project is referencing this document isn't an issue, I will have that somewhere, I just need to know how to run a query.. is that possible?
Upvotes: 1
Views: 1295
Reputation: 2049
I was able to accomplish the desired effect by using Mongooses Middleware functionality. Setting up the validation inside the pre-save hook worked just fine
Upvotes: 2