arrays - Mongoose 中的子文档数组

标签 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 类型的对象数组。但我收到以下错误

数组“eventFAQs”处未定义类型“undefined”

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

最佳答案

尝试:

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

编辑

模型.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)
}

关于arrays - Mongoose 中的子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43534461/

相关文章:

ruby - 在 ruby​​ 中按类或 kind_of 分隔列表项

javascript - Nodejs响应中的汉字写入

php - 如何在 phalcon 中将 "group by"、 "having"查询从 mysql 转换为 mongodb

javascript - 受限制的 JavaScript Array Pop Polyfill 不起作用

javascript - 在对象内迭代数组并相应地添加属性

javascript - NodeJS - 服务器响应 404,然后加载页面

linux - 无法在ubuntu中启动mongo shell

spring - 使用 Spring Data MongoDB 中的 MongoTemplate 进行查找查询时仅投影某些字段?

c - 读取文件时如何更改数组值

javascript - 从文件中获取 4 个字节并将其转换为时间戳