Search code examples
node.jsmongoose-schema

How to buld a nested schema working in mongoose?


I want build an app on NodeJs which will analyze some information that i will input. Currently i can code for one schema. But i cant do nested. Can anybody help me through this. Thanks in advance.

var provinceSchema = new mongoose.Schema({ city: String });

Inside every city i want to put temparture, population.


Solution

  • You can create a schema for the city and add few fields that are required like as cityname, temparature, populations and so on as below.

    const cityDetailsSchema = new Schema({
      cityname: {
        type: String,
        max: 24,
        required: [true, 'Please enter cityname']
      },
      temparature: {
        type: String,
        required: true
      },
      populations: {
        type: Number,
        required: true
      },
      nested: cityDetailsNestedSchema
    
      // you can create more fields like as above.
    
    });
    
    const cityDetailsNestedSchema = new Schema({
        keyName: { 
            type: String, 
            lowercase: true, 
            trim: true 
         } 
    })