如何解决如何为聚合查询返回相交的匹配项?
我有一个abTest
集合的以下架构:
const AbTestSchema = new Schema({
name: {
type: String,unique: true,},validCountryCodes: [
{
type: String,enum: ['GB','AU','US','FR'],],status: {
type: String,enum: ['active','draft','inactive'],default: 'draft',required: true,});
通过我的API创建或编辑AB测试时,我想确保对于任何特定active
只能有一个状态为countryCode
的测试。
例如,如果存在一个带有validCountryCodes
列表的['GB',AU']
的活动测试,并且用户想要创建一个带有['GB']
列表的另一个活动测试,则将抛出错误。已经有GB
个用户的有效测试,因此可以避免。
我具有以下功能并进行汇总查询,以查找符合要求的国家/地区代码的有效测试:
const getActiveAbTestsByCountryCodes = async (countryCodes: string[]) => {
const matches = await AbTest.aggregate([
{
$match: { validCountryCodes: { $in: countryCodes },status: 'active' },{
$project: {
countryCodeMatch: {
$setIntersection: ['$validCountryCodes',countryCodes],sizeMatch: {
$size: {
$setIntersection: ['$validCountryCodes',{ $match: { sizeMatch: { $gte: 1 } } },{
$project: {
countryCodeMatch: 1,]);
return { activeTestCount: matches.length };
};
如果'GB'
是validCountryCodes
之一的活动测试已经存在,并且测试创建尝试通过了['GB','AU']
,则上面的查询将返回以下内容:
[ { _id: 5f5f3a9f9bcf5e0e91387aff,countryCodeMatch: [ 'GB' ] } ]
在createAbTestService
中这样使用:
const createAbTest = async params => {
if (status === 'active') {
const { activeTestCount } = await getActiveAbTestsByCountryCodes(
params.validCountryCodes,);
if (activeTestCount > 0) {
throw new ValidationError({
message: onlyOneActiveTestPerCountryCode,});
}
}
const abTest = await AbTest.create(params);
return abTest;
};
现在,错误消息模糊不清,仅告诉用户已经存在有效的测试。
如何更新聚合查询以返回在活动测试中找到的国家代码+测试名称?
我希望查询结果如下:
{ testsAlreadyActiveFor: ['GB','AU'],matchesFoundIn: ['test443','test445'] },
这样,我可以返回错误消息,例如:There is already an active test for the countryCodes: ${testsAlreadyActiveCode}. Please check the following active tests: ${matchesFoundIn}
我该怎么做?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。