【问题标题】:Mongoose, proper way to update documents with deep nested schemas猫鼬,使用深层嵌套模式更新文档的正确方法
【发布时间】:2018-06-08 21:25:43
【问题描述】:

我想知道更新其中也包含嵌套模式的文档的最有效方法是什么。通常我只会使用Model.findByIdAndUpdate(id, updatedValues) ...,但是如果我尝试对具有深层嵌套模式的文档执行此操作,我会收到此错误:CastError: Cast to Embedded failed for value "{ _id: 5b1936aab50e727c83687797, en_US: 'Meat', lt_LT: 'Mesa' }" at path "title".

我的架构看起来像:

const titleSchema = new Schema({
    en_US: {
        type: String,
        required: true
    },
    lt_LT: {
        type: String,
        default: null
    }
})

const categorySchema = new Schema({
    title: titleSchema
});

const ingredientSchema = new Schema({
    title: {
        type: titleSchema,
        required: true
    },
    category: categorySchema,
    calories: {
        type: Number,
        min: 0,
        default: 0
    },
    vitamins: [String]
})

我尝试像这样更新:

{
    title: {
        en_US: 'Pork',
        lt_LT: 'Kiauliena'
    },
    category: {
        _id: '5b193a230af63a7e80b6acd8',
        title: {
            _id: '5b193a230af63a7e80b6acd7'
            en_US: 'Meat',
            lt_LT: 'Mesa'
        }
    }
}

注意,我仅使用类别_id 从单独的集合中获取新类别对象,但进入findByIdAndUpdate() 函数的最终更新对象与上面的类似。

我发现的唯一方法是从更新的值中删除类别,通过findByIdAndUpdate() 更新文档,获取更新的文档,为其分配新类别并保存。

它工作得很好,但这需要两次调用数据库,是否可以一次完成?

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    尝试像这样更新您的架构:

    const titleSchema = new Schema({
        en_US: {
            type: String,
            required: true
        },
        lt_LT: {
            type: String,
            default: null
        }
    });
    
    const ingredientSchema = new Schema({
        title: {
            type: titleSchema,
            required: true
        },
        category: {
            title: titleSchema
        },
        calories: {
            type: Number,
            min: 0,
            default: 0
        },
        vitamins: [String]
    });
    

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      相关资源
      最近更新 更多