0

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 ?

3
  • What do you mean, "link"? What does your schema look like now? Commented Nov 17, 2013 at 20:36
  • For this case, I would prefer embedding instead of linking. Just embed "values" field to product document Commented Nov 18, 2013 at 14:26
  • Indeed I finally used embedding :) I was too stuck with my relational mind :) Commented Nov 21, 2013 at 14:07

1 Answer 1

3

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],
})
Sign up to request clarification or add additional context in comments.

1 Comment

@AlexGrs know this is a long time ago but did this help :p in that case could you mark it as correct answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.