Alex Grs
Alex Grs

Reputation: 3301

How to link to sub-document using mongoose & node.js

Is it possible using Node.js, Express and Mongoose for MongoDB to have a link to a sub-document.

He is one of my document containing platforms sub-Documents:

// 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"
        }
    ]
}

I also have a Variable document which have sub-document related to platforms:

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

In Mongoose, is it possible to have a schema reflecting it ?

Upvotes: 0

Views: 1559

Answers (1)

Mattias Farnemyhr
Mattias Farnemyhr

Reputation: 4238

You can either do this:

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

or this:

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

Upvotes: 3

Related Questions