Doubt regarding Nodejs and Mongoose

Asked

Viewed 144 times

-2

Hello I started to study nodejs and I have a question regarding connections with database and relationships, Using Mongoose I made this schema:

const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate');

const ProductSchema = new mongoose.Schema({
    //propriedades / campos no db
    nome:{
        type:String,
        required:true,
    },
    preco:{
        type:String,
        required:true,
    }
});

ProductSchema.plugin(mongoosePaginate); //paginar a reposta

mongoose.model('Product', ProductSchema); // registrando o model na aplicação  ( toda aplicação vai saber que existe um model product com essas colunas no db)

But then a question arose when I thought of a relationship, an example (simple only to try to understand the solution):

inserir a descrição da imagem aqui

My doubt is how I could make these models in the nodejs the Mongoose would be the best option in this case?

In case I would have to create, productCategory and category too? But how would I relate these 2 to productCategory?

I’d be grateful if someone could help me with that question.

  • Mongoose is a connection to Mongodb, which is a non-relational database, see tutorials on what and how databases are used by documents. You don’t make relationships like that, you try to have everything in one document to be much simpler and faster to access the data... It is not necessary data schema since it is all JSON and there is no schema limit...

  • @balexandre I’ll take a look, as it is faster and simpler would be better than relational ? hehe vc could tell me some negative points of it? And you would indicate using it ? or have situations that it is not feasible to use it.

  • has so many articles and videos on Youtube with the good and bad points that it is not worth answering here, because I need many more lines to write :) look here a video

1 answer

0


Let me get this straight, you have two Collections, and you’re looking to create a third Collection that referenced the previous two. With that the code looks something like this:

Schema productoCategory

const ProdutoCategoriaSchema = new mongoose.Schema({
produto:{
    type: mongoose.schema.types.objectId, 
    ref: 'Product', // esse nome faz referência ao nome que colocou na Collection
    require: true
},
categoria:{
    type: mongoose.schema.types.objectId, 
    ref: 'categoria', 
    require: true
},

});

I suggest you watch this video where it is applied something similar to this your problem:

https://www.youtube.com/watch?v=GAZdUyIV3ms

Rocketseat: https://www.youtube.com/channel/UCSfwM5u0Kce6Cce8_S72olg

Browser other questions tagged

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