如何在猫鼬中通过查询引用对象获取数据



我遇到了一个问题,但未能找到我正在寻找的内容。 我也有这个Ads模式,还有其他人的参考:

link: {
type: String,
default: 'n/a',
},
page: {
type: mongoose.Schema.ObjectId,
ref: 'AdsPage',
required: true,
},
slot: {
type: mongoose.Schema.ObjectId,
ref: 'AdsSlot',
required: true,
},

我想通过在page属性上应用条件来获取数据,page是一个包含 url 属性的架构。 页面架构:

{
title: {
type: String,
required: [true, 'Please add page title'],
unique: true,
trim: true,
maxlength: [50, 'Name cannot be more then 50 characters'],
},
url: {
type: String,
required: [true, 'Add page URL'],
},
createdAt: {
type: Date,
default: Date.now,
},
},

我想获取与提供的网页网址匹配的所有广告。

我的查询如下所示:

if (req.params.pageUrl) {
const ads = await Ads.find({
'page.url': req.params.pageUrl,
});
return res.status(200).json({
success: true,
message: 'Successfully fetched ads for specific page',
count: ads.length,
data: ads,
});
}

参数中的页面 URL 很好,但不知何故这个过滤器不起作用,我没有收到错误,但结果为零。 我已经尝试了$match属性,但遇到了一些上层错误。

非常感谢对嵌套 ref 对象查询的任何帮助。

您可以使用aggregate$lookup来执行此操作。您可以在聚合中看到更多详细信息。

您的输出ads_pages就是您的adspages。聚合数组中的第一个元素,$lookup将帮助您找到所有匹配的条件,该条件在adspage中_id等于广告中的pageurladspage中等于您的req.params.pageUrl

聚合数组中的第二个元素,$match将帮助您删除包含空ads_pages的文档,这意味着其条件与上述条件不匹配。您可以使用此 https://jsfiddle.net/cuxvd2pm 进行测试。

await AdsModel.aggregate([
{
$lookup: {
// This name must be same as your collection name "in the mongodb"
// In my case, I must use lowercase string, and add more extra "s" in the end
// If you didn't modify extra configuration, I think you should also do it.
from: "adspages",
// you could use as: "page" to replace the original field
as: "ads_pages",
let: { "page_id": "$page"},
pipeline: [{ 
$match: {
$expr: {
$and: [
{$eq: ["$url", req.params.pageUrl]},
{$eq: ["$_id", "$$page_id"]}
]
}
}
}]
}
},
{
$match: {
// when you change your `as field` to page
// you should also change `ads_pages.0` to `page.0`
"ads_pages.0": {
$exists: true
}
}
}
])

最新更新