How to create “array of arrays of objects” schema in Mongoose.js

荒凉一梦 提交于 2020-08-10 19:34:27

问题


I need to create schema for following data structure:

{
  ...
  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}],
  ]
}

I tried to do so like this while defining my schema, but it caused validation errors:

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

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

it seems that such a schema syntax is supported now in Mongoose (https://github.com/Automattic/mongoose/issues/1361).


回答1:


Sample code to create Array of arrays of object:

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



来源:https://stackoverflow.com/questions/52944240/how-to-create-array-of-arrays-of-objects-schema-in-mongoose-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!