1

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
  • Using matrix: [[]] solves the problem. But what about defining schema for cellSchema ? Commented Oct 23, 2018 at 15:53

1 Answer 1

4

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 enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.