假设我有一个 id 字符串,看起来像 557fba5a8032a674d929e6a1
存储在 session 中。我尝试检索一个文档,其 _id
与上面相同,但即使它存在我也找不到它。
Posts.findOne({_id: "557fba5a8032a674d929e6a1"});
返回未定义。现有对象如下所示:
![enter image description here](https://i.sstatic.net/9ZdCX.png)
我可以通过这样做来使它工作
var id = "557fba5a8032a674d929e6a1";
var posts = Posts.find().fetch();
var post = _.filter(posts, function (post) { return post._id._str === id });
return post
但它看起来很脏。这是我的控制台输入和输出,用于进一步调查此行为 (
Posts == Applicants
)。你会注意到,即使我们要找的文件肯定存在,我也找不到。![enter image description here](https://i.sstatic.net/YuLZK.png)
最佳答案
您必须将 _id 定义为 Mongo.ObjectID
代表ObjectID正确键入。
Posts.findOne({_id: new Mongo.ObjectID("557fba5a8032a674d929e6a1") });
使用 Meteor 的 ObjectID 的一个警告是它们的时间戳不正确。特别是当它们插入客户端时。
关于 meteor 找到一个带有 id 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30884874/