2017-01-28 76 views
0

我有一個包含兩個模式(用戶和帖子)的MongoDB數據庫。它曾經是這樣的:使用Mongoose將字符串字段轉換爲MongoDB中的ObjectID字段

username: {type: String}, 
following: {type: [String], ref: 'users'} 

user_id: {type: String, ref: 'users'} 
comment: {type: String} 

但現在我已經決定從字符串更改參考字段的類型OBJECTID所以現在我有:

username: {type: String}, 
following: {type: [Schema.Types.ObjectId], ref: 'users'} 

user_id: {type: Schema.Types.ObjectId, ref: 'users'} 
comment: {type: String} 

但在數據庫中的舊數據仍然存儲爲字符串。我怎樣才能正確地遷移這些數據?

我使用Mongoose從我的代碼中查詢數據庫。

+0

是串有效'ObjectId'十六進制值? – chridam

+0

@chridam是的,他們是。 – CorrieSparrow

+0

我想你應該使用model.find({})所有的文章文檔,然後循環遍歷每個文檔和文檔。 user_id = mongoose.Types.ObjectId(doc.user_id);並在每個文檔上做doc.save –

回答

1

您應該使用 model.find({})來獲取所有文件後,通過每個文檔循環之後,並更新每個文件

doc.user_id = mongoose.Types.ObjectId(doc.user_id); 
doc.save(); 
相關問題