Doubt about Mongodb’s relational Schema

Asked

Viewed 145 times

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 already have it inside my bank (Survey) this populated information:

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

How do I make a reference with the id above?

If I do it the way down, um _id random will be created and there will be no link with the top model.

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

Another question is this: How to generate, at once, a single json with all the information of these two schemes ?

  • Let me understand, you want to know how to override the _id for an existing value and you want to generate a Join between the two schemas?

  • @Khaosdoctor wanted to generate a Join between the two schemes. After that, I would like to generate a json with all the information that has been added. How to do this?

1 answer

2


To set the ID to an existing value you can do it in two ways. The first is to explicitly declare the _id in his 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 else you can disable the auto generation of _idwith , { _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 within Surveys a list of documents that are your pages, that is, when you use find it will already assemble for you a complete JSON structure, because you are referencing another schema within the first one. But maybe the method populate whatever you’re looking for, see here:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.