2

I'm trying to query for a specific element inside an array in a Meteor collection on the client side, but Minimongo doesn't support the $ operator. Is there an alternative to filter my query so it returns just the specific element in the array?

My collection is structured like this:

{
  "userID": "abc123",
  "array": [
    {
      "id": "foo",
      "propA": "x",
      "propB": "y"
    },
    {
      "id": "bar",
      "propA": "a",
      "propB": "b"
    }
  ]
}

I am trying to write a query that returns just the object in the array with id "foo". In Mongo, that query would be this:

collection.find({
  "userID": "abc123",
  "array.id": "foo"
}, {
  "array.$": 1
});

However, Minimongo doesn't support the $ operator in projections so this throws an error. I've tried similarly structured queries using $elemMatch, and attempted the solution described here but it doesn't accomplish what I'm trying to do.

Is there an alternative means of querying for the one element in this array with Minimongo?

Community
  • 1
  • 1
Josh Vickerson
  • 429
  • 5
  • 16

1 Answers1

3

You can use findWhere to extract the first matching object in an array. Give something like this a try:

// Find all documents matching the selector.
const docs = Collection.find({ userId: 'x', 'array.id': 'y' }).fetch();

// For each document, find the matching array element.
for (let doc of docs) {
  let obj = _.findWhere(doc.array, { id: 'y' });
  console.log(obj);
}
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • I actually used find().fetch() and it did exactly what I was looking for. If you edit the answer I'll mark it correct. – Josh Vickerson Mar 24 '16 at 20:49
  • @JoshVickerson Have a look at the proposed edits. I'm still unclear if you are searching for an element in a single or multiple documents. – David Weldon Mar 25 '16 at 05:18
  • I'm looking for an element inside a single document. In my use case, the userId is guaranteed to be unique, so the find should only ever match one document. I then need a single element from the array in that document. – Josh Vickerson Mar 31 '16 at 18:33
  • Huh. I'm surprised then that the original solution didn't work: `_.findWhere(Collection.findOne({userId: 'x'}).array, {id: 'y'})` – David Weldon Mar 31 '16 at 18:40