How do I make appends on Mongoose models?

Asked

Viewed 101 times

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

1 answer

2


the ideal would be you reference as follows in your Model.

Example:

user: {
   type: mongoose.Schema.Types.ObjectId, //aqui é a referencia ao id 
   ref: 'User' //Nome da "tabela"
},

I think in your case it would look like this in your Company.js:

thumbnail: {
   type: mongoose.Schema.Types.ObjectId, //aqui é a referencia ao id 
   ref: 'Thumbnail' //Nome da "tabela"
},

Browser other questions tagged

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