Search code examples
mongodbexpressmongoosedatabase-designmongoose-schema

How to create schema setup for multiple cities?


I am going to create a to/do app with the mern stack, I want to have multiple countries and cities in the application.

For the design of the project, should I create a master schema with a country name and array of cities, with a following array embedded for the type of post.

Then I can use this schema for x countries and thus when I need to load posts for a user Canada, Vancouver, the posts will be stored in a very specific location, making the search very easy.

If you have experience in this kind of setup, please advise, thanks.


Solution

  • Try to create mongoose schema as below.

    It will be helpful for your requirements

    //Country Schema
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var Country = new Schema({
        CountryID: { type: String, default: "" },
        Country_Name: { type: String, default: "" },
        Country_Code: { type: String, default: "" },//Mobile
        Country_Currency: { type: String, default: "" },//Business or Ecommerce
        location: { //for Map Purpose
            longitude: Number,
            latitude: Number
        },
        Point: { type: [Number], index: '2d' },
    }, { collection: 'Country' });
    Country.index({ Point: '2dsphere' });
    module.exports = mongoose.model('Country', Country);
    
    
    //City Schema
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var City = new Schema({
        CityID: { type: String, default: "" },
        CountryID: { type: String, default: "" },
        City_Name: { type: String, default: "" },
        location: { //for Map Purpose
            longitude: Number,
            latitude: Number
        },
        Point: { type: [Number], index: '2d' },
    }, { collection: 'City' });
    City.index({ Point: '2dsphere' });
    module.exports = mongoose.model('City', City);