1

Hi im really struggling finding a solution to this.

Im trying to see if an array contains a value that I give

I want all tickets of a specific organization.

The organization is saved in the user (Creator) in an array named organizations.

Models

ticket {
    creator: "ObjectId"
}

user {
    organizations: ["ObjectId", "ObjectId"]
}

This is what I have now

    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"}},
    ])

This doesn't work tho

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.

1
  • 1
    $elemMatch is not required, because you have already unwind the creator array, just try { $match: { "creator.organizations": {"$in": [ObjectId("60a77d5b57d8c960829a0343")]} } } Commented May 21, 2021 at 15:54

1 Answer 1

1

$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"
    }
  },
])

Sign up to request clarification or add additional context in comments.

2 Comments

That just sends an empty array. I double checked the objectId from organizations and it should return a ticket.
Add the objectId from organizations as a mongoose ObjectId (instead of a string). I modified the answer to reflect this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.