【问题标题】:How to create "array of arrays of objects" schema in Mongoose.js如何在 Mongoose.js 中创建“对象数组的数组”模式
【发布时间】:2019-03-27 09:47:12
【问题描述】:

我需要为以下数据结构创建架构:

{
  ...
  matrix: [
    [{type: "A", count: 6}, {type: "B", count: 4}],
    [{type: "B", count: 1}, {type: "A", count: 2}, {type: "A", count: 1}],
    [{type: "C", count: 7}, {type: "A", count: 1}],
  ]
}

我在定义架构时尝试这样做,但它导致了验证错误:

const cellSchema = new mongoose.Schema({
  type: String,
  count: Number
});

const matrixSchema = new mongoose.Schema({
  ...
  matrix: [[cellSchema]]
});

现在 Mongoose (https://github.com/Automattic/mongoose/issues/1361) 似乎支持这种模式语法。

【问题讨论】:

  • 使用matrix: [[]] 解决了这个问题。但是为cellSchema 定义模式呢?

标签: mongodb mongoose mongoose-schema


【解决方案1】:

创建对象数组的示例代码:

const cellSchema = new mongoose.Schema({
    type: String,
    count: Number
});

const matrixSchema = new mongoose.Schema({
    matrix: [[cellSchema]]
});

const Matrix = mongoose.model('Matrix', matrixSchema);

const newMatrix = new Matrix({
    matrix: [
        [{ type: 'xyz', count: 10 }, { type: 'ABC', count: 20 }],
        [{ type: 'pqr', count: 10 }]]
});
newMatrix.save();

Output

【讨论】:

    猜你喜欢
    • 2015-05-25
    • 2018-11-30
    • 2014-04-10
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多