Meo在Mongo.Collection中无法通过id找到

时间:2016-05-07 00:21:59

标签: mongodb meteor minimongo

我正在尝试按_id选择一条记录,但它不起作用。

我在javascript控制台中遇到与Meteor代码相同的问题,所以为了简单起见,我将在控制台中运行一个示例。

我的收藏中有两个Article。我将从服务器发布此集合:

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

在客户端订阅:

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

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

我可以在控制台中验证这些是否已通过Articles.find().fetch()进入客户端:

Articles.find().fetch()

从在线示例来看,看起来我应该能够Articles.find({_id: id})Articles.findOne(id),但没有任何作用:

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

可以通过任何其他属性 findfindOneArticles.findOne({title: "Dog eats Poop"})正确返回记录:

findOne with the title attribute works

这里发生了什么?

1 个答案:

答案 0 :(得分:3)

在输入此内容后不久,我偶然发现an old StackOverflow issue a Meteor issue that was closed in 2013指向meteor mongo控制台中创建的记录处理字符串,Mongo.ObjectId处理不同。

所以我尝试了Articles.findOne(new Mongo.ObjectID("572bdb811ab1829622aeee78"))而不是Articles.findOne("572bdb811ab1829622aeee78")并且它有效:

casting the id as a Mongo.ObjectID works

那么......到底是什么。示例代码中没有一个显示需要将id转换为Mongo.ObjectID,并且最初提出这个问题的问题已在三年前关闭。