Search code examples
mongodbmeteorminimongo

Meteor can't find by id in a Mongo.Collection


I'm trying to select a record by it's _id, but it's not working.

I'm having the same problems in the javascript console as in the Meteor code, so I'll run through an example in the console for simplicity.

I have two Articles in my collection. I'm publishing this collection from the server:

if(Meteor.isServer){
  Meteor.publish('articles', function articlesPublication() {
    return Articles.find();
  });
}

And subscribing to it on the client:

export default createContainer(() => {
  Meteor.subscribe('articles');

  return {
    articles: Articles.find().fetch(),
  };
}, App);

I can verify that these are getting to the client with Articles.find().fetch() in the console:

Articles.find().fetch()

From examples online, it looks like I should be able to do Articles.find({_id: id}) or Articles.findOne(id), but nothing works:

Articles.find(id) doesn't work in the console

I can find and findOne by any other attribute, though. Articles.findOne({title: "Dog eats Poop"}) correctly returns the record:

findOne with the title attribute works

What's going on here?


Solution

  • Shortly after typing this out I stumbled on an old StackOverflow issue that pointed to a Meteor issue that was closed in 2013 that records created in the meteor mongo console treat strings and Mongo.ObjectIds differently.

    So I tried Articles.findOne(new Mongo.ObjectID("572bdb811ab1829622aeee78")) instead of Articles.findOne("572bdb811ab1829622aeee78") and it worked:

    casting the id as a Mongo.ObjectID works

    So... what the heck. None of the example code shows the need to cast ids to a Mongo.ObjectID, and the issue that brought this up originally was closed three years ago.