Doubt about MongoDb relational schema

1
const SurveySchema = new Schema({
    name: String,
    pages: [ //um survey pode ter várias páginas
        {
            type: Schema.Types.ObjectId,
            ref: 'Page'
        }
    ]
});

const PageSchema = new Schema({
    name: String, 
    description: String,
    _type: String
});

const Page = mongoose.model('Page', PageSchema);
const Survey = mongoose.model('Survey', SurveySchema);

Let's say I have already populated information inside my bank ( Survey ):

{
    _id: 'survey1',
    name: 'Algum nome',
    pages: ['58ff555', '123456789'] // Coleção de id's; cada id é uma página
}

How do I reference the above id?

If I do this in the way below, a random% wrap will be created and there will be no link to the template above.

var pag = new Page({
    name: 'joeys',
    description: 'descricao 1'
});
pag.save(function(err, model) {
    if (err)
        res.send(err);
    res.json(model);
});

Another question: How to generate a single json with all the information from these two schemes at once?

    
asked by anonymous 25.04.2017 / 18:17

1 answer

2

To set the ID to an existing value you can do it in two ways. The first is to explicitly declare _id in your model:

const SurveySchema = new Schema({
    _id: Number,
    name: String,
    pages: [ //um survey pode ter várias páginas
        {
            type: Schema.Types.ObjectId,
            ref: 'Page'
        }
    ]
});

Or you can disable auto-generation of _id with , { _id: false } :

const SurveySchema = new Schema({
    _id: Number,
    name: String,
    pages: [ //um survey pode ter várias páginas
        {
            type: Schema.Types.ObjectId,
            ref: 'Page'
        }
    ]
}, {_id: false});

As for join, you already have a list of documents inside your surveys, that is, when you use find it will already mount for you a complete JSON structure, since you are referencing another schema within the first. But maybe the populate method is what you are looking for, see here:

25.04.2017 / 18:48