2
I have a model in Mongoose that references another model, and I need to bring the data of this other model in my controller, follow code:
Model Empresa.js:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
nome: {
type: String,
required: true
},
thumbnail_id: {
type: Number,
required: true
},
});
module.exports = mongoose.model('Empresa', schema);
Note that I have the thumbnail_id field in this model and I need to return the thubmnail data in the controller, follow the second model I have to return:
Model Thubmnail.js:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
usuario: {
type: String,
required: false
},
thumbnail: {
type: String,
required: false
},
});
module.exports = mongoose.model('Media', schema);
Follows current return:
{
"_id": "5d9e4623c745c70d2c05e418",
"nome": "Teste",
"thumbnail_id": 1,
"__v": 0
}
Follows expected return:
{
"_id": "5d9e4623c745c70d2c05e418",
"nome": "Teste2",
"thumbnail_id": 1,
"media": {
"usuario": "Teste",
"thumbnail": "uploads/thumb.jpg",
},
"__v": 0
}
The following is an interesting link of relationships, including Umparamuitos: https://stackoverflow.com/questions/35245685/mongoose-one-to-many/35245953
– Alan PS