2014-02-22 28 views
2

我使用mongoimport將大量csv文件導入到流星集合中,但是當它們進行插入時,_id值是ObjectID,而流星使用字符串ID。在流星文檔中有一個關於ObjectIDs的小例子,但我並不真正瞭解我應該做什麼。例如,使用鐵路由器我有像這樣如何使用mongoimport的ObjectID?

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類型的對象,看起來像http://localhost:3000/profiles/ObjectID(%22530845da3621faf06fcb0802%22)。它也不返回任何內容,頁面呈現空白。這是出版物。

Meteor.publish('singleProfile', function(id, userId) { 
    return Profiles.find({ 
     _id: id, 
     userId: userId, 
     forDel: { 
      $ne: true 
     } 
    }); 
}); 

我想我的問題是,我怎麼使用的ObjectID讓路由只使用對象ID的字符串部分,以及如何正確返回的數據?

更新:我已經設法通過將鏈接從<a href="{{pathFor 'profileView'}}" class="profile-details">Details</a>更改爲<a href="/profiles/{{_id._str}}" class="profile-details">Details</a>來獲取ObjectID脫離url,所以url現在是http://localhost:3000/profiles/530845da3621faf06fcb0802。不幸的是,頁面仍呈現空白,我不確定是否因爲我訂閱,發佈或查找收藏品的方式。

+1

如果用'new Meteor.Collection.ObjectID(this.params._id)'替換'this.params._id'的所有實例會發生什麼? – sbking

+0

@Cuberto我得到一個錯誤'從Deps重新計算異常:錯誤:無效的十六進制字符串創建ObjectID' – landland

+0

@landland你只能使用括號中的東西,即'ObjectID(%22530845da3621faf06fcb0802%22)你需要'530845da3621faf06fcb0802'作爲'this.params.id' – Akshat

回答

2

總結評論跟帖作爲一個答案:

的對象ID的字符串部分可以通過簡單地調用._str上的ID爲

id._str 

獲得您也可以從一門手藝的對象ID十六進制字符串使用

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) 
}); 

一般來說,與對象ID的工作時,你會發現自己需要一些反模式從字符串轉換爲對象ID或反之亦然,因此類似下面的程序會派上用場:

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周邊的指針和問題使用Ob jectID的。

相關問題