如何使用猫鼬和节点链接到子文档.js



是否可以使用MongoDB的Node.js,Express和Mongoose来链接到子文档。

他是我的文档之一,包含平台子文档:

// A product description
{
    "name": "My product",
    "operator": "5288c2bdb0269e1c85000003",
    "_id": "528909ff1225faa801000004",
    "platforms": [
        {
            "name": "Platform 1",
            "_id": "528909ff1225faa801000007"
        },
        {
            "name": "Platform 2",
            "_id": "528909ff1225faa801000006"
        },
        {
            "name": "Platform 3",
            "_id": "528909ff1225faa801000005"
        }
    ]
}

我还有一个变量文档,其中包含与平台相关的子文档:

// Variable description
{
    "name": "My variable",
    "values": [
        {
            "platform": "528909ff1225faa801000007",
            "values": "value 1"
        },
        {
            "platform": "528909ff1225faa801000006",
            "values": "value 2"
        },
        {
            "platform": "528909ff1225faa801000005",
            "values": "value 3"
        }
    ]
}

在猫鼬中,是否有可能有一个反映它的模式?

你可以这样做:

ProductSchema = new Schema({
    name: {type: String},
    operator: {type: Schema.Types.ObjectId},
    platforms: [{
        name: {type: String},
    }],
})

或者这个:

ProductSchema = new Schema({
    name: {type: String},
    operator: {type: Schema.Types.ObjectId},
    platforms: [PlatformSchema],
})

最新更新