我有两种模式。

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
    }]
})


我正在尝试嵌入FAQ类型的对象数组。但是我收到以下错误

Undefined type 'undefined' at array 'eventFAQs'

我知道我缺少对象数组的基本概念。但是我花了很多时间试图找出原因,而我自己却无法解决。

最佳答案

尝试:

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


编辑

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);


用法:

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

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

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


结果:

{
    "_id" : ObjectId("58f99d1a193d534e28bfc70f"),
    "title" : "Title",
    "eventFAQs" : [
        {
            "question" : "Question",
            "answer" : "Answer",
            "_id" : ObjectId("58f99d1a193d534e28bfc70e")
        }
    ],
    "__v" : NumberInt(0)
}

08-18 11:07
查看更多