I have a Mongoose abTest
document that has two fields:
status
. This is a string enum and can be of typeactive
,inactive
ordraft
.validCountryCodes
. This is an array of strings enums (GB
,EU
,AU
etc). By default, it will be empty.
In the DB, at any one time, I only want there to be one active abTest
for each validCountryCode
so I'm performing some validation prior to creating or editing a new abTest
.
To do this, I've written a function that attempts to count the number of documents that have a status
of active
and that contain one of the countryCodes
.
The function will then return if the count is more than one. If so, I will throw a validation error.
if (params.status === 'active') {
const activeTestForCountryExists = await checkIfActiveAbTestForCountry(
validCountryCodes,
);
if (params.activeTestForCountryExists) {
throw new ValidationError({
message: 'There can only be one active test for each country code.',
});
}
}
const abTest = await AbTest.create(params);
checkIfActiveAbTestForCountry()
looks like this:
const checkIfActiveAbTestForCountry = async countryCodes => {
const query = {
status: 'active',
};
if (
!countryCodes ||
(Array.isArray(countryCodes) && countryCodes.length === 0)
) {
query.validCountryCodes = {
$eq: [],
};
} else {
query.validCountryCodes = { $in: [countryCodes] };
}
const count = await AbTest.countDocuments(query);
return count > 0;
};
The count query should count not only exact array matches, but for any partial matches.
If in the DB there is an active
abTest
with a validCountryCodes
array of ['GB', 'AU',]
, the attempting to create a new abTest
with ['GB'
should fail. As there is already a test with GB
as a validCountryCode
.
Similarly, if there is a test with a validCountryCodes
array of ['AU']
, then creating a test with validCountryCodes
of ['AU,'NZ']
should also fail.
Neither is enforced right now.
How can I do this? Is this possible write a query that checks for this?
I considered iterating over params.validCountryCodes
and counting the docs that include each, but this seems like bad practice.