2016-09-22 78 views
0

我正在尋找一些在Mongo中的_id的幫助。我想手動設置一個ObjectId()引用,但我不能這樣做。我檢查了官方mongo文檔中的代碼並將其插入到我的應用中,但失敗了。如果有人能提供一些見解,我將不勝感激。 original_id變量是我想要設置的。這是一個鏈接到蒙戈文檔 - https://docs.mongodb.com/manual/reference/database-references/#document-references和代碼如下。任何幫助/見解都會很棒。手動參考 - ObjectId()

Template.postNewJob.events({ 
     'submit form': function(event) { 
      event.preventDefault(); 
      original_id = ObjectId(); 
      var position = $('[name=position]').val(); 
      var jobDescription = $('[name=jobDescription]').val(); 
      var createdAt = new Date(); 
      var createdBy = Meteor.userId(); 
      postedJobs.insert({ 
       _id: original_id, 
       position: position, 
       jobDescription: jobDescription, 
       createdAt: createdAt, 
       createdBy: createdBy 
      }); 
      Router.go('dashboard'); 
     } 
    }); 
+0

「我做不到」是什麼意思?如果您收到任何錯誤,請添加錯誤或解釋您獲得的結果。 –

+0

@AminJ - 「我不能這樣做」意味着如果我聲明像original_id = ObjectId(); - 它不會用新的對象ID設置變量。另外,我得到的錯誤是「Uncaught ReferenceError:ObjectId沒有定義」 - 謝謝。 – Mike

回答

0

我能弄明白。我需要按以下方式設置它: var original_id = new Meteor.Collection.ObjectID()。valueOf();

0
> meteor shell 
Welcome to the server-side interactive shell! 

Tab completion is enabled for global variables. 

Type .reload to restart the server and the shell. 
Type .exit to disconnect from the server and leave the shell. 
Type .help for additional help. 

> Coll = new Mongo.Collection('coll') 

默認插入,流星將生成_id

> Coll.insert({str: "blah"}) 
'JTeBKdTErXWQyedMN' 

插入通過的ObjectID對象作爲_id

> Coll.insert({_id: new Meteor.Collection.ObjectID(), str: "blah"}) 
{ [String: '8dbfd702d76d6152685e2f66'] _str: '8dbfd702d76d6152685e2f66' } 

插入使用用戶構造String作爲_id

> Coll.insert({_id: "1234", str: "blah"}) 
'1234' 

當然如果你cr eate自己的_id值,你有責任確保_ids不集合中已經存在,或者您的刀片將被拒絕:

> Coll.insert({_id: "1234", str: "blah"}) 
WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error index: meteor.coll.$_id_ dup key: { : \"1234\" }","op":{"_id":"1234","str":"blah"}}) 
... more stack trace follows 

並且在這之後您的收藏樣子:

> Coll.find({}).fetch() 
[ { _id: 'JTeBKdTErXWQyedMN', str: 'blah' }, 
    { _id: { [String: '8dbfd702d76d6152685e2f66'] _str: '8dbfd702d76d6152685e2f66' }, 
    str: 'blah' }, 
    { _id: '1234', str: 'blah' } ] 

> Coll.findOne('JTeBKdTErXWQyedMN') 
{ _id: 'JTeBKdTErXWQyedMN', str: 'blah' } 

> Coll.findOne('1234') 
{ _id: '1234', str: 'blah' } 

> Coll.findOne(new Meteor.Collection.ObjectID('8dbfd702d76d6152685e2f66')) 
{ _id: { [String: '8dbfd702d76d6152685e2f66'] _str: 8dbfd702d76d6152685e2f66' }, str: 'blah' }