Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor finding an object with id

Tags:

meteor

Assume I have an id string that looks like 557fba5a8032a674d929e6a1 which is stored in session. I try to retrieve a document whose _id is same as above, but I fail to find it even though it exists.

Posts.findOne({_id: "557fba5a8032a674d929e6a1"});

returns undefined. The existing object looks like following:

enter image description here

I can make it work by doing

var id = "557fba5a8032a674d929e6a1";
var posts = Posts.find().fetch();
var post = _.filter(posts, function (post) { return post._id._str === id });
return post

but it seems dirty. Here's my console inputs and outputs to further investigate this behavior (Posts == Applicants). You will notice that even though the document that we are looking for definitely exists, I can't find it.

enter image description here

like image 758
Maximus S Avatar asked Jun 17 '15 07:06

Maximus S


2 Answers

You have to define _id as a Mongo.ObjectID to represent the ObjectID type correctly.

Posts.findOne({_id: new Mongo.ObjectID("557fba5a8032a674d929e6a1") });

One caveat of ObjectIDs with Meteor is their timestamps aren't correct. Particularly if they're inserted on the client.

like image 131
Tarang Avatar answered Nov 07 '22 14:11

Tarang


Akshat's answer will probably work, but new Mongo.ObjectID("557fba5a8032a674d929e6a1") will generate a new ID and if you are trying to update a record or find a record it won't find any.

I would do something like this:

function findPostById(id) {
  let newMongoObjectId = new Mongo.Collection.ObjectID();
  newMongoObjectId._str = id;
  Posts.findOne({_id: newMongoObjectId._str});
}
like image 24
raihan Avatar answered Nov 07 '22 15:11

raihan