2016-03-17 35 views
0

有沒有辦法爲新文檔生成ID?本地生成ID以避免由mongodb自動創建

喜歡的東西

var newID = mongoose.Types.ObjectId(); 

// some random code that may involve db operations. 

db.Model.create({_id: newID, otherProperties: {}}) 

當我寫這樣的事情,在創建的文檔的實際ID總是比NEWID稍大。無論如何要準確使用newID嗎?

+2

當我嘗試相同的方法時,此代碼正常工作。你能提供[mcve]嗎? – JohnnyHK

+0

至少使用自己的ID字段 –

回答

0

您不應該爲mongodb文檔創建ID屬性,它會在創建它們時自動爲所有文檔生成ID屬性。

e.x

db.users.insert({name:'kasun',email:'[email protected]',address:'2street,colombo'}) 

這將克里特島的屬性稱爲_id爲kasun.It的文件是unique.Therefore沒有設置ID屬性手動。

+0

'db.Model.create({otherProperties:{}})'skip define _id :,所有文檔默認自動添加_id –

+0

我在問是否有方法手動設置它爲y? – user1017674

+0

?這是沒用的 –