我使用 mongoimport 将一堆大型 csv 文件导入到 Meteor 集合中,但是当它们进行插入时,_id 值是 ObjectID,而 Meteor 使用字符串 id。 meteor 文档 here 中有一个关于 ObjectID 的小简介。但我真的不明白我应该做什么。例如,使用 Iron Router 我有一条像这样的路线
this.route('profileView', {
path: '/profiles/:_id',
notFoundTemplate: 'notFound',
fastRender: true,
waitOn: function() {
return [Meteor.subscribe('singleProfile', this.params._id, Meteor.userId())];
},
data: function() {
Session.set('currentProfileId', this.params._id);
return Profiles.findOne({
_id: this.params._id
}, {
fields: {
submitted: 0
}
});
}
但是路由的 url 是 object 类型,看起来像 http://localhost:3000/profiles/ObjectID(%22530845da3621faf06fcb0802%22)
。它也不会返回任何内容,页面呈现空白。这是出版物。
Meteor.publish('singleProfile', function(id, userId) {
return Profiles.find({
_id: id,
userId: userId,
forDel: {
$ne: true
}
});
});
我想我的问题是,我应该如何使用 ObjectID 以便路由仅使用 ObjectID 的字符串部分,以及如何正确返回数据?
更新:我通过更改 <a href="{{pathFor 'profileView'}}" class="profile-details">Details</a>
中 View 的链接,成功地从 url 中获取了 ObjectID。至<a href="/profiles/{{_id._str}}" class="profile-details">Details</a>
所以现在的网址是 http://localhost:3000/profiles/530845da3621faf06fcb0802
。不幸的是,该页面仍然呈现空白,我不确定这是否是因为我订阅、发布或查找收藏项的方式所致。
最佳答案
总结评论线程作为答案:
ObjectID 的字符串部分可以通过简单地在 id 上调用 ._str 来获取
id._str
您还可以使用十六进制字符串制作 ObjectID
new Meteor.Colletion.ObjectID(hexstring)
因此,当您使用 <a href="/profiles/{{_id._str}}" class="profile-details">Details</a>
访问路线时你可以像这样制作你的发现:
Profiles.findOne({
_id: new Meteor.Collection.ObjectID(this.params._id)
});
一般来说,在使用 ObjectID 时,您会发现自己需要一些反模式来从字符串转换为 objectId,反之亦然,因此像下面这样的实用程序会派上用场:
IDAsString = this._id._str ? this._id._str : this._id
和
IDAsObjectId = this._id._str ? this._id : new Meteor.Collection.ObjectID(this._id)
另请参阅 github.com/meteor/meteor/issues/1834 和 groups.google.com/forum/#!topic/meteor-talk/f-ljBdZOwPk,了解有关使用 ObjectID 的指导和问题.
关于meteor - 如何使用 mongoimport 中的 ObjectID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958757/