Node.js 如何返回聚合查询的相交匹配项?
对于Node.js 如何返回聚合查询的相交匹配项?,node.js,mongodb,mongoose,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,对于abTest集合,我有以下模式: const AbTestSchema = new Schema({ name: { type: String, unique: true, }, validCountryCodes: [ { type: String, enum: ['GB', 'AU', 'US', 'FR'], }, ], status: { type: String, enum: ['activ
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测试时,我想确保对于任何特定的countryCode
,只有一个测试的active
状态
例如,如果有一个活动测试的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', countryCodes],
},
},
},
},
{ $match: { sizeMatch: { $gte: 1 } } },
{
$project: {
countryCodeMatch: 1,
},
},
]);
return { activeTestCount: matches.length };
};
如果活动测试已经存在,其中'GB'
是有效国家代码之一
,并且测试创建尝试通过['GB',AU']
,则上述查询将返回以下内容:
[{u 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;
};
现在,错误消息很模糊,只告诉用户活动测试已经存在
如何更新聚合查询以返回在活动测试中找到的countryCodes+测试名称
我希望查询的结果如下所示:
{testsalReadyActivieFor:['GB','AU',matchesFoundIn:['test443','test445']},
这样我就可以返回一条错误消息,比如:已经有一个针对countryCodes的活动测试:${testsAlreadyActiveCode}。请检查以下活动测试:${matchesFoundIn}
如何执行此操作?尝试使用
$addFields
而不是$project
,这样会将名称保留在结果集中。