【问题标题】:Save arrays in Mongoose schema在 Mongoose 模式中保存数组
【发布时间】:2017-12-30 12:03:46
【问题描述】:

假设我想要一个数据模式:每个用户都可以拥有许多笔记本电脑,有些笔记本电脑可用,有些则没有。 我希望我能得到一些类似的架构,

User
| userId: 1
| laptops:
   | laptopId: 1  available: true  //default
   | laptopId: 2  available: true  

如何定义这样的架构? 以下不正确:

const User = new mongoose.Schema({
  userId: {
    type: String,
    index: { unique: true }
  },
  laptops: {
    laptopId: String,
    available: Boolean
  }
});

如何在 node.js 中的 Mongoose 中定义这个?

【问题讨论】:

    标签: node.js mongodb mongoose-schema


    【解决方案1】:

    您只需使用方括号,如本例所示:

    const User = new mongoose.Schema({
      userId: {
        type: String,
        index: { unique: true }
      },
      laptops: [{
        laptopId:{
            type: String
        },
        available: {
            type: Boolean
        }
      }]
    });
    

    查看official docs for allowed SchemaTypes.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2014-03-02
      • 2014-06-21
      • 2015-07-18
      • 2020-05-15
      相关资源
      最近更新 更多