Mongoose中的子文档数组

时间:2017-04-21 05:17:34

标签: arrays node.js mongodb mongoose mongoose-schema

我有两个架构。

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'

我知道我错过了对象数组的基本概念。但是我花了很多时间试图找出原因并且无法自己解决。

1 个答案:

答案 0 :(得分:1)

尝试:

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