Meteor detected an object with an identifier

Suppose I have an id string that looks like 557fba5a8032a674d929e6a1

which is stored in the session. I am trying to get a document whose _id

is the same as above, but I cannot find it even if it exists.

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

      

returns undefined. The existing object looks like this:

enter image description here

I can get it to 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 ins and outs for further exploring this behavior ( Posts == Applicants

). You will notice that although the document we are looking for definitely exists, I cannot find it.

enter image description here

+3


source to share


3 answers


You must define _id as Mongo.ObjectID

to represent the ObjectID correctly .

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

      



One warning about Object IDs with Meteor is incorrect timestamps. In particular, if they are inserted on the client.

+5


source


Akshat's answer will probably work, but new Mongo.ObjectID("557fba5a8032a674d929e6a1")

will create a new id and if you try to update a record or find a record it won't find it.

I would do something like this:



function findPostById(id) {
  let newMongoObjectId = new Mongo.Collection.ObjectID();
  newMongoObjectId._str = id;
  Posts.findOne({_id: newMongoObjectId._str});
}

      

+1


source


This is what works for me:

var id = "557fba5a8032a674d929e6a1";
Posts.findOne({'_id.str': id});

      

Hope it helps

0


source







All Articles