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:
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.
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.
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});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With