5

I have two schemas.

FAQ Schema 

const EventFAQSchema = mongoose.Schema({
    question: { type: String, req: true },
    answer: { type: String, req: true }
});

EventSchema 

const EventSchema = mongoose.Schema({
   "title": { type: String },
   "description": { type: String },
   "eventFAQs": [{
       type: EventFAQSchema ,
       default: EventFAQSchema 
    }]
})

I am trying to embed an array of objects of type FAQ. But I get the following error

Undefined type 'undefined' at array 'eventFAQs'

I know I am missing a fundamental concept of array of objects. But I have spent a good deal of time trying to find out the reason and couldn't resolve it myself.

Giridhar Karnik
  • 2,213
  • 4
  • 27
  • 47

1 Answers1

10

Try with:

"eventFAQs": {
    type: [ EventFAQSchema ],
    default: [{
        question: "default question",
        answer: "default answer"
    }]
}

EDIT

model.js

const mongoose = require('mongoose');

const EventFAQSchema = mongoose.Schema({
    question: { type: String, required: true },
    answer: { type: String, required: true }
});

const EventSchema = mongoose.Schema({
    "title": { type: String },
    "description": { type: String },
    "eventFAQs": {
        type: [ EventFAQSchema ],
        default: [{
            question: 'Question',
            answer: 'Answer'
        }]
    }
});

module.exports = mongoose.model('Event', EventSchema);

Usage:

const Event = require('./model.js');

var e = new Event({
    title: "Title"
});

e.save(function (err) {
    console.log(err); // NO ERROR
});

Result:

{ 
    "_id" : ObjectId("58f99d1a193d534e28bfc70f"), 
    "title" : "Title", 
    "eventFAQs" : [
        {
            "question" : "Question", 
            "answer" : "Answer", 
            "_id" : ObjectId("58f99d1a193d534e28bfc70e")
        }
    ], 
    "__v" : NumberInt(0)
}
luisenrike
  • 2,742
  • 17
  • 23
  • This gives me an embedded document, where as I need an embedded document array – Giridhar Karnik Apr 21 '17 at 08:43
  • When I loop through the req and make an array of EventFAQ and put that while creating Event Document, only defaults "Question" and "Answer" is being taken. – Giridhar Karnik Apr 21 '17 at 08:52
  • This works too: `var faqs = [{ question: 'question1', answer: 'answer1' }, { question: 'question2', answer: 'answer2' }, { question: 'question3', answer: 'answer3' }];` and `var e = new Event({ title: "Title", eventFAQs: faqs }); ` – luisenrike Apr 21 '17 at 15:26
  • new mongoose.Schema() ?? i thought there should be ```new``` keyword – MartianMartian Mar 07 '22 at 07:16