Reputation: 77
I want all tickets of a specific organization.
The organization is saved in the user (Creator) in an array named organizations.
ticket {
creator: "ObjectId"
}
user {
organizations: ["ObjectId", "ObjectId"]
}
Ticket.aggregate([
{
"$lookup": {
"from": User.collection.name,
"localField": "creator",
"foreignField": "_id",
"as": "creator"
}
},
{ "$unwind": "$creator" },
{ "$match": { "creator.organizations": {
"$elemMatch": {"$in": ["60a77d5b57d8c960829a0343"]}}}
},
{ "$set": {"creator": "$creator._id"}},
])
I read that you can't use $elemMatch inside an aggregate because its a query. How do I achieve this? I've seen people saying to use a $filter but I have no clue how to make that.
Upvotes: 1
Views: 39
Reputation: 649
$elemMatch
is not required here. This can be achieved only using $match
as shown below.
const mongoose = require("mongoose");
Ticket.aggregate([{
"$lookup": {
"from": User.collection.name,
"localField": "creator",
"foreignField": "_id",
"as": "creator"
}
},
{
"$unwind": "$creator"
},
// Modified code
{
"$match": {
"creator.organizations": mongoose.Types.ObjectId("60a77d5b57d8c960829a0343")
}
},
{
"$set": {
"creator": "$creator._id"
}
},
])
Upvotes: 1