2015-04-03 166 views
0

對於任何玩「激戰2」的人來說,這個模式可能看起來很熟悉。我試圖通過他們的API下載所有項目,並且無法獲取嵌入的「細節」屬性以編組和/或持續。這是我用貓鼬首次嘗試,所以我希望這裏有一個昭然若揭的問題:Mongoose嵌入式文檔不保存

這裏是我的架構定義:

var ItemSchema = new Schema({ 
    _id: Number, 
    name: String, 
    icon: String, 
    description: String, 
    type: String, 
    rarity: String, 
    level: Number, 
    vendor_value: Number, 
    default_skin: Number, 
    flags: [String], 
    game_types: [String], 
    restrictions: [String], 
    details: {    // This is the problem property 
     type: String, 
     weight_class: String, 
     defense: Number, 
     infusion_slots: { 
      flags: [String], 
      item_id: Number 
     }, 
     infix_upgrade: { 
      attributes: [{ 
       attribute: String, 
       modifier: Number 
      }], 
      buff: { 
       skill_id: String, 
       description: String 
      } 
     }, 
     suffix_item_id: Number, 
     size: Number, 
     no_sell_or_sort: Boolean, 
     description: String, 
     duration_ms: Number, 
     unlock_type: String, 
     color_id: Number, 
     recipe_id: Number, 
     charges: Number, 
     flags: [String], 
     infusion_upgrade_flags: [String], 
     suffix: String, 
     bonuses: [String], 
     damage_type: String, 
     min_power: Number, 
     max_power: Number 
    } 
}); 

我試圖通過兩個插入保存傳入對象和findOneAndUpdate(upsert)。

var gwItem = // grab from API. 
Item.remove({_id: gwItem.id}).exec(); 
// At this point, details looks like an object property. 
gwItem['_id'] = gwItem.id; 
var item = new Item(gwItem); 
// At this point, calling item.toObject() shows no 'details' property set... 
item.save().exec(); // 'details' not saved here 
// Do below in replacement of item.save(); 
gwItem['$setOnInsert'] = {_id: gwItem.id}; 
// This saves 'details' property with a value of '[object Object]'... 
Item.findOneAndUpdate({_id: gwItem.id}, gwItem, {upsert:true}, function(){}); 

什麼樣的API發送和填充到「gwItem」上面的代碼示例:https://api.guildwars2.com/v2/items/68743

我在做什麼錯?

回答

1

這是因爲Mongoose如何定義模式。由於您使用關鍵字type作爲details的路徑名,因此它將details定義爲String字段,其​​餘路徑爲details的選項。只需將type: String更改爲type: {type: String},即可完成設置。更多信息here