2013-01-16 56 views
6

我的文檔包含一個名爲clients的字段,該字段應該包含一個客戶端ID的數組。在Mongoose中填充ObjectId的數組

{ 
    "first_name":"Nick", 
    "last_name":"Parsons", 
    "email":"[email protected]", 
    "password":"foo", 
    "clients":[ 
    "50f5e901545cf990c500000f", 
    "50f5e90b545cf990c5000010" 
    ] 
} 

我的數據是作爲JSON來的,我直接發送給Mongo來創建一個文檔。出於某種原因,我在創建時沒有填充clients,所以我必須以字符串的形式手動輸入它們。

我的模式是相當簡單的,並定義爲:正確

var userSchema = new Schema({ 
    first_name: { 
     type: String, 
     trim: true 
    }, 
    last_name: { 
     type: String, 
     trim: true 
    }, 
    email: { 
     type: String, 
     trim: true, 
     lowercase: true, 
     index: true, 
     unique: true, 
     required: true 
    }, 
    password: String, 
    clients: [Schema.Types.ObjectId] 
}); 

從我的理解,我定義的客戶。但是我在創建時無法讓客戶端數組填充。事件傳遞給mongo的原始對象看起來不錯。

{ 
    first_name: 'Zack', 
    last_name: 'S', 
    email: '[email protected]', 
    password: 'test', 
    clients: [ 
     '50f5e901545cf990c500000f', 
     '50f5e90b545cf990c5000010' 
    ] 
} 

有什麼特別的,我必須做我的輸入,以便它被正確鑄造?

回答

2

接受的答案可能已經過時......

如果你要更新這個集合,我會建議使用$推送更新。此更新方法旨在避免在您所做的所有操作都追加到集合中的數組時執行更新。

http://docs.mongodb.org/manual/reference/operator/update/push/

+0

請給你的推薦技巧在貓鼬身上展示一些例子。 –

+1

示例可以在提供的鏈接中找到.. http://docs.mongodb.org/manual/reference/operator/update/push/#examples –

10

簡單修復。檢查傳入數組是否已填充。如果是這樣,我循環遍歷每個並將轉換後的ObjectId版本推送到數組中。顯然mongoose.Types.ObjectId('STRING');能夠將一般字符串轉換爲有效的貓鼬身份證。

// if clients was passed with associated client ids 
if (data.clients.length > 0) { 

    _.map(data.clients, function(cid) { 

     // push client id (converted from string to mongo object id) into clients 
     user.clients.push(mongoose.Types.ObjectId(cid)); 

    }); 

} 

希望這可以幫助別人。

+1

不會推送重複的user.clients的內容? –

+0

我如何在你的地圖函數中填充例如'cid's' –

+0

@PraktikBothra否,因爲他在循環data.clients時推入user.clients。 –