Home > Software design >  Unable to create Nested Schemas in mongodb
Unable to create Nested Schemas in mongodb

Time:08-29

I have two Schemas in mongoose : User and Detail and I want to add the Detail model in User model as a nested Schema. Following are the two Schemas as mentioned above for more clarity.

User.js

const mongoose=require("mongoose");
const Schema=mongoose.Schema;
const complaintSchema=require("./Complaint");
const detailSchema=require("./Detail");

const userSchema=new Schema({
    username:{type:String,required:true,unique:true},
    email:{type:String,required:true,unique:true},
    password:{type:String,required:true},
    detailsFilled:{type:Boolean,default:false},
    details:{type:detailSchema.Schema},
    complaints:{type:[complaintSchema.Schema]}
},{timestamps:true});

module.exports=mongoose.model("Users",userSchema);

Detail.js

const mongoose=require("mongoose");
const Schema=mongoose.Schema;

const detailSchema=new Schema({
    firstname:{type:String,required:true},
    lastname:{type:String,required:true},
    telephone:{type:Number,required:true},
    hostel:{type:String,required:true},
    hostelFees:{type:String,required:false},
    roomNo:{type:String,required:true},
},{timestamps:true});

module.exports=mongoose.model("Details",detailSchema);

The detail field in User Schema should contain single Detail Schema object per user(not an array of Detail objects). But the User.js code shows an error saying:

TypeError: Invalid value for schema path `details.type`, got value "undefined"

Can someone please help me sort this error.

CodePudding user response:

Try This:

details:{
    type:Schema.Types.ObjectId,
    ref: "Details"
}

You need to provide the type of field and then the ref to that field after the type.

  • Related