如何在Mongoose.js中创建“对象数组”模式

时间:2018-10-23 08:15:54

标签: mongodb mongoose mongoose-schema

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

{
  ...
  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)现在支持这种架构语法。

1 个答案:

答案 0 :(得分: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 enter image description here

相关问题