【问题标题】:How to set data default in embedded document mongoose schema如何在嵌入式文档猫鼬模式中设置数据默认值
【发布时间】:2022-12-31 03:51:44
【问题描述】:

我正在使用嵌入式文档,我已经为此模型模式设置了默认数据,但是当我尝试创建一个新文档时,集合返回了空数组。在猫鼬的模型模式中添加新文档时如何设置默认集合?

我的模型架构定义:

const ActionSchema= new mongoose.Schema({
  canEdit: {
    type: Boolean,
    default: true
  },
  canDelete: {
    type: Boolean,
    default: false
  },
  canMention: {
    type: Boolean,
    default: true
  }
});

const PostSchema = new mongoose.Schema({
  title: String,
  detail: String,
  author: Schema.Types.ObjectId,
  action: [ActionSchema]
});

每次添加新帖子时都应该自动添加默认数据,如下所示:

{
  title: 'Happy New Year',
  detail: 'Happy New Year 2024',
  author: ObjectId(...),
  action: [
    {
       canEdit: true,
       canDelete: false,
       canMention: true
    }
  ]
}

【问题讨论】:

    标签: node.js database mongodb mongoose nosql


    【解决方案1】:

    您只指定类型为ActionSchema 的数组,但为什么要在数组中创建项目?如果需要,您还需要为 action 字段指定默认值:

    const PostSchema = new mongoose.Schema({
      title: { type: String },
      detail: { type: String },
      author: { type: Schema.Types.ObjectId },
      action: { 
        type: [ActionSchema], 
        default: [
          canEdit: true,
          canDelete: false,
          canMention: true
        ]
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 2020-05-14
      • 2015-02-26
      • 2014-02-13
      • 2020-11-01
      • 2012-04-29
      • 1970-01-01
      相关资源
      最近更新 更多