Home > Back-end >  What is the correct way to create a data model?
What is the correct way to create a data model?

Time:09-17

Beginner here, I want to create a data model with Mongoose like this:

{
 "country": "Spain"
 "products": [
          {
            "product": "product1"
            "price": "5"
          },
          {
            "product": "product2"
            "price": "8"
          }
 ]
}

I've seen some tutorials but every single one of them creates just products (not nested like mine is). Or is it even the right strategy? Or is it a better solution to create something like this?

{
 "country": "Spain",
 "product": "product1",
 "price": 10, 
},
{
 "country": "Spain",
 "product": "product2",
 "price": 15, 
},
{
 "country": "Germany",
 "product": "product1",
 "price": 12, 
}

In this case, I know how to do it:

mongoose.model('Product', { 
  "country": { type: String, required: true },
  "product": { type: String, required: true }, 
  "price": { type: Number, required: true }
})

But in the first case, I don't know how to create it. Overall my intention is to be able to display products that will be grouped by countries.

CodePudding user response:

There are several options: First, you could use subdocuments They allow you to define products inside the Country schema.

  import mongoose from 'mongoose';
  const { Schema } = mongoose;

  const countrySchema = new Schema({
    products: [{ name: {type: String}, price: {type: Number} }],
    name: {type: String}
  });
export default mongoose.model('Country', countrySchema);

Another way would be to define 2 different models, and have a many-many relationship between the 2, meaning one country can "own" many products and a product can belong to many countries. This would allow you to query countries and products separately, but also see which product a country has or which countries a product belongs to. This works like this: You can see about how to declare and query such models here


const productSchema = new Schema({
    name: {type: String},
    price: {type: Number},
    countries: [{type: mongoose.Schema.Types.ObjectId, ref: "Country"}]
})
const ProductModel = mongoose.model('Product', productSchema);

const countrySchema = new Schema({
    products: [{type: mongoose.Schema.Types.ObjectId, ref: "Product" }],
    name: {type: String}
  });
const CountryModel = mongoose.model('Country', countrySchema);

CodePudding user response:

I think the second strategy is right And if you want group product by country you could use $group in aggregate function if mongo or mongodb

  • Related