在猫鼬中查找条件 [英] lookup with condition in mongoose
问题描述
我有两个收藏.文章和书签.
I have two collections. articles and bookmarks.
{
_id: "5faa889ade5e0a6326a873d3",
name: "article 1"
},
{
_id: "5faa889ade5e0a6326a873d",
name: "article 2"
}
书签
{
_id: "5faa889ade5e0a6326a873d1",
user_id: "5fc7b50da483a66a86aa7e9e",
model_id: "5faa889ade5e0a6326a873d3"
}
我想加入带有书签的文章.如果用户将文章加为书签.我尝试过的
I want to join article with bookmark. if user bookmarked a article. what i have tried
const aggregate = await Articles.aggregate([{
$lookup: {
from: "categories",
localField: "category_id",
foreignField: "_id",
as: "category_id"
}
},
{
$lookup: {
from: "bookmarks",
localField: "_id",
foreignField: "model_id",
as: "bookmarks"
}
}
]);
但是它将不仅为用户书签登录,还为文章提供所有书签.那么我该如何添加条件.
but it will gives all bookmark for the article not only logged in user bookmark. so how can I add a condition.
{ "user_id": objectId(req.user._id) } // logged user id
推荐答案
您可以使用 MongoDB v3.4 , 这篇关于在猫鼬中查找条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! _id
作为 model_id
变量传递,您可以使用$$引用在查找管道中使用字段, $ match
阶段并匹配您所需的条件和 user_id
条件
_id
as model_id
variable, you can use the field inside lookup pipeline using $$ reference,$match
stage and match your required conditions and user_id
condition {
$lookup: {
from: "bookmarks",
let: { model_id: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$model_id", "$model_id"] },
user_id: objectId(req.user._id)
}
}
],
as: "bookmarks"
}
}
书签
,并根据条件获取过滤的书签
bookmarks
and get filtered bookmarks on the base of condition {
$lookup: {
from: "bookmarks",
localField: "_id",
foreignField: "model_id",
as: "bookmarks"
}
},
{
$addFields: {
bookmarks: {
$filter: {
input: "$bookmarks",
cond: { $eq: ["$$this.user_id", objectId(req.user._id)] }
}
}
}
}