首页 > 解决方案 > 猫鼬 - 如何让子文档符合模式

问题描述

所以我有以下模式:

var Item_Detail = new Schema(
    {
        content: {
            index: true,
            type: Array
        },
        is_private: {
            default: false,
            index: true,
            type: Boolean
        },
        order: {
            index: true,
            required: true,
            type: Number
        },
        table: {
            default: {},
            type: Object
        },
        title: {
            required: true,
            index: true,
            type: String,
        },
        type: {
            default: "text",
            enum: ["text", "table"],
            index: true,
            type: String
        },
    },
    {
        strict: false
    }
)

const Item = new Schema(
    {
        details: {
            default: [],
            index: true,
            type: [Item_Detail],
        },
        display_name: {
            default: "",
            index: true,
            type: String,
        },
        image: {
            default: "http://via.placeholder.com/700x500/ffffff/000000/?text=No%20Image&",
            type: String
        },
        is_private: {
            default: false,
            index: true,
            type: Boolean
        },
        tags: {
            index: true,
            type: [Tag]
        }
    },
    {
        strict: false
    }
)

现在,Item_Detail将成为 的子文档Item,但我不太确定应该如何执行defaults 和type限制。我也不想Item_Detail自己成为一个集合,所以使用createsave可能不适合。

标签: javascriptmongodbmongoosemongoose-schema

解决方案


我认为您可以为此使用嵌入式文档,因此在您的项目模式中您可以嵌入item_detail:

const Item = new Schema({
    ...
    item_detail: item_detail
})

然后在服务器上,当您要添加 item_detail 时,您可以执行以下操作

myItem = new Item({//enter item data here})
//assign item detail here
myItem.item_detail = item_detail ;

然后继续保存

myItem.save()

推荐阅读