2013-04-07 42 views
3

我有一個動態數據模型,有幾個靜態字段,其餘都是動態的。例如使用Mongoose的動態子文檔

var item1 = { 
    title:'Door', 
    price: 30, 
    color:{selected:'blue', options:['blue', 'red']}, // dynamic 
    material:{selected:'wood', options:['iron', 'wood', 'plastic']} 
} 

var item2 = { 
    title:'T-Shirt', 
    price: 5, 
    color:{selected:'green', options:['blue', 'green']}, // dynamic 
    size:{selected:'XL', options:['XL', 'L']} // dynamic 
} 

被標記爲動態的字段在架構定義上是不知道的,而新的一次可以動態出現。 架構我創建看起來像這樣:

var itemSchema = mongoose.Schema({ 
    title: String, 
    price: Number 
}); 

好像貓鼬存儲動態字段,但在「發現」這些字段返回爲BLOB和的toJSON()/ toObject()刪除它們。有沒有辦法將它們轉換回子文檔?

回答

1

根據我的經驗,Mongoose不保存模式中未定義的內容。根據您的itemSchema,除了titleprice之外的任何內容都不會被保存。

根據您提供的代碼,我假定顏色,尺寸和材料可能存在也可能不存在,但如果它們是,則它們都遵循相同的格式:與selectedoptions鍵對象。所以,你可能想嘗試Mongoose Subdocuments

var selectionSchema = new Schema({ 
    selected:String, 
    options:Array 
}); 

var itemSchema = mongoose.Schema({ 
    title: {type:String, required:true}, 
    price: {type:Number, required:true}, 
    color: selectionSchema, 
    material: selectionSchema, 
    size: selectionSchema 
}); 

注意,不需要colormaterialsize鍵,這仍然允許他們是動態的。如果數據存在,鍵+數據將被保存。如果沒有數據存在,他們的密鑰也不會被保存。

UPDATE:

正如您在您的評論中提到,你不知道所有的動態性能放在首位。在這種情況下,如果你在模式爲「空白」對象指定屬性,貓鼬會允許任何和所有屬性空白對象,像這樣:

var itemSchema = mongoose.Schema({ 
    title: {type:String, required:true}, 
    price: {type:Number, required:true}, 
    selection:{} 
}); 

這裏,selection關鍵 - 是一個「空白「對象 - 可以保存size,color,material或任何其他鍵。他們不需要事先知道。您仍然可以使用selectionSchema來強制執行該子對象的鍵值&。

+0

如果我知道前面所有的動態屬性,這可能會奏效。問題在於,明天我可能會發生一個叫做age的新屬性。 – 2013-04-08 10:10:10

+0

'{}'不適合我。該文檔仍然保存,但沒有該字段中的屬性。 – 2016-02-15 13:16:18