Home > Software design >  How to make a nested Schema in Nodejs
How to make a nested Schema in Nodejs

Time:11-23

name:"salman,

protein:23,

carbs:23,

calorie:1221,

fats:12,

ingredients:{

salt:1 teaspoon,

......

} I want a schema like this how can I make a schema of this with nodejs mongoose also how can i add data in this nested schema because am getting error

CodePudding user response:

Initially you have to create the table schema like this:

const mongoose = require('mongoose');

// Health Schema
const HealthSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    protein: {
        type: String,
    },
  carbs: {
    type: String,
  },
  calorie: {
    type: String,
  },
  fats: {
    type: String,
  },
  ingredients: {
    type: object,
    default: {
      salt: '',
      fibre: ''
    }
  },
});

module.exports = mongoose.model(
    'health',
    HealthSchema
);

Here ingredients objects have priorly set the keyname. So you have to just pass the value at the time of creation.

CodePudding user response:

I'm gonna skip alot of things here.

In your schema do something like,
ingredients:[String]

when creating new data do something like

const healtData= await new healtData({... the data here})

the do something like this before calling save

healthData.ingredients.push(ingredient)

healthData.save()

  • Related