Skip to content

[Bug] [[[Number]]] does not want to save my [[]] array correctly #9215

@cyrilgandon

Description

@cyrilgandon

I have a triple nested array defined in mongoose. When I try to initialize it with a 2 level deep empty array, it adds a third level. See the following code:

import mongoose, { Schema } from 'mongoose';

const foos = mongoose.model(`FooModel`, new Schema({ numbers: [[[Number]]] }));
const oneFoo = await foos.create({ numbers: [[]] });
console.log(oneFoo.numbers);

Expected: [[]], Actual: [[[]]]

Wrap up

  • with [[[Number]]]
    • [] gives [] ✅
    • [[]] gives [[[]]] ❌
  • with [[Number]]
    • [] gives [] ✅

Versions:

"mongodb": "3.5.4",
"mongoose": "5.9.22",

The actual code only check for depth of the current value, and if it matches the depth of the declared Schema. The problem I see is that it doesn't check if values are actually array before wrapping everything into an array.

      if (valueDepth.min === valueDepth.max && valueDepth.max < depth) {
        for (let i = valueDepth.max; i < depth; ++i) {
          value = [value];
        }
      }

The way it is, it looks like it should loop over the entire array to find if depth is not sufficient AND if items are not arrays.

Reproductible unit test:

  it('doesnt wrap empty nested array with insufficient depth', function() {
    const weekSchema = mongoose.Schema({
      days: {
        type: [[[Number]]],
        required: true
      }
    });

    const Week = db.model('Test', weekSchema);
    const emptyWeek = new Week();

    emptyWeek.days = [[], [], [], [], [], [], []];
    const obj = emptyWeek.toObject();
    assert.deepEqual(obj.days, [[], [], [], [], [], [], []]);
  });

Maybe @vkarpov15 can have an idea on how to fix it, you already take care of a lot of bug on this type of issue (2b9d3b1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions