【问题标题】:How do I use ObjectID from a mongoimport?如何使用来自 mongoimport 的 ObjectID?
【发布时间】:2014-02-25 06:40:38
【问题描述】:

我使用 mongoimport 将一堆大型 csv 文件导入到流星集合中,但是当他们执行插入时,_id 值是 ObjectID,而流星使用字符串 id。在流星文档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> 更改为<a href="/profiles/{{_id._str}}" class="profile-details">Details</a>,我已经设法从url 中取出ObjectID,因此url 现在是http://localhost:3000/profiles/530845da3621faf06fcb0802。不幸的是,页面仍然显示为空白,我不确定这是不是因为我订阅、发布或查找收藏项的方式。

【问题讨论】:

  • 如果用new Meteor.Collection.ObjectID(this.params._id) 替换所有this.params._id 实例会发生什么?
  • @Cuberto 我收到一个错误Exception from Deps recompute: Error: Invalid hexadecimal string for creating an ObjectID
  • @landland 您只需要使用括号中的内容,即对于ObjectID(%22530845da3621faf06fcb0802%22),您需要将530845da3621faf06fcb0802 作为this.params.id
  • @Akshat。没运气。当我打印到控制台时, this.params._id 是 530845da3621faf06fcb0802 但页面仍然呈现空白。发布和路由代码在其他方面保持不变。
  • objectid的字符串部分,只需在id上调用._str即可。另外,请查看 github.com/meteor/meteor/issues/1834groups.google.com/forum/#!topic/meteor-talk/f-ljBdZOwPk 以获取指针

标签: meteor


【解决方案1】:

总结评论线程作为答案:

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 的指针和问题.

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2011-06-08
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多