Mongoose嵌入式文档不保存

时间:2015-04-03 15:09:46

标签: node.js mongodb mongoose

对于玩“激战2”的人来说,这个架构可能看起来很熟悉。我正在尝试通过他们的API下载所有项目,并且无法获取嵌入式的详细信息'属于封存和/或坚持的财产。这是我第一次尝试使用猫鼬,所以我希望这里有一个明显的问题:

这是我的架构定义:

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
    }
});

我试图通过insert和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 个答案:

答案 0 :(得分:1)

这是因为Mongoose定义了模式。由于您使用关键字type作为details的路径名,因此将details定义为String字段,其余路径则是details的选项。只需将type: String更改为type: {type: String}即可。更多信息here