Search code examples
node.jsmongodbexpressmongoose-schema

How to create documents and sub-documents at same time in Node Mongo DB mongoose Express App


I'm getting below details from registration screen, How can I create sub-documents in Node mongo express mongo app. I'm new to node js and mongo db, not able to understand how to create sub-documents from registration page (20+ fields getting from registration page, I give below schema with fewer fields)

{
    fullname: 'Some Name',
    // Sub document
    education: {
        degree: 'Graduation',
        college: 'Some College'
    },
    // Sub document
    questions: [
        { qns: 'Question 1', ans: 'Answer1' }
        { qns: 'Question 2', ans: 'Answer2' }
    ]
}

Solution

  • You mean this!

    
        const Student = Schema({
            fullname:{
              type: String,
              required: false,
              default: ''
            },
            questions: [
              new mongoose.Schema({
                ans: {
                  type: String,
                  required: false,
                  default: ''
                },
                que: {
                  type: String,
                  required: false,
                  default: ''
                }
              })
            ]
        })