【问题标题】:How to write a key-value pair object Schema in mongoose如何在猫鼬中编写键值对对象模式
【发布时间】:2021-07-03 06:33:38
【问题描述】:

我已经努力创建这样的架构,但还没有找到解决方案。

我试图做这样的事情。

 questions: {
    type: new Schema({
      questionId: {
        type: String,
      },
      correct: {
        type: Boolean,
      },
    }),
  },

我需要的输出是:

questions: {
  [questionId1]:[boolean],
  [questionId2]:[boolean]
}

例子:

questions:{
 23:true,
 29:false
}

提前致谢。

【问题讨论】:

  • 我认为我需要使用 type:Map 但不知道如何在我的情况下使用它。

标签: json database mongodb object mongoose


【解决方案1】:

正如 saksh73 已经指出的那样(https://mongoosejs.com/docs/schematypes.html#maps),可以使用 Map 来完成架构

const Example = new Schema({
    // your stuff
    questions: {
        type:Map,
        of: Boolean
    }
});

【讨论】:

    【解决方案2】:

    您可以使用以下方法添加布尔键值对:

    const abc = new Schema({
          questionId: {
            type: Map,
            of:Boolean
          },
    });
    

    如果你想要一个对象而不是布尔值......你可以这样做:

    const abc = new Schema({
          questionId: {
            type: Map,
            of:new Schema({
              id: Number,
              title: String,
            }),
          },
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多