Home > Enterprise >  How do I fetch specific data when I select an option? MERN Stack
How do I fetch specific data when I select an option? MERN Stack

Time:03-10

I want to make a MERN application for car sales. Every car has its own brand and model. I want that when I select a brand, for example BMW, to get BMW models such as X3, X6, Serie 3 ... When I select Audi, the model should be A6, A5, Audi 80 ... How to do it? How do you make a mongoose model for something like that? Can anyone give me an idea how to do something like that. Nothing comes to mind at the moment.

CodePudding user response:

you need to put models under cars in your MongoDb document like below, check below Mongo collection structure.

{
  "_id": {
    "$oid": "6227f6861b3a9764567e8eb3"
  },"cars":[{
    "name": "BWM",
    "Model": ["x1","x2","x3"]
   }]
}  

CodePudding user response:

might be this Help you. by creating two different schema models.for better data management.

const mongoose = require("mongoose");

const schema = new mongoose.Schema(
  {
    name: {
      type: String,
      index: true
    },
    company: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'company',
      index: true
    },
    type: {
      type: String,
      index: true
    },
    launchDate: {
      type: Date
    },
    variant: {
      type: String
    }
  },
  {
    versionKey: false,
    timestamps: true,
  }
);

module.exports = mongoose.model("models", schema);

const company = new mongoose.Schema(
  {
    name: {
      type: String,
      index: true
    }
  },
  {
    versionKey: false,
    timestamps: true,
  }
);

module.exports = mongoose.model("company", company);
  • Related