Search code examples
mongodbmongoosemongoose-schema

what is difference between [{type: String}] and {type: [String]} in mongoose?


i was trying to get data such that if no value is assigned to field, it should not appear in the collection.

i tried this:

const CollectionSchema = new Schema({
  field1: [{ type: String, default: undefined}],
});

OR

const CollectionSchema = new Schema({
  field1: [{ type: String, default: () => undefined}],
});

which didn't worked, and whenever i tried to create it empty field1:[] showed up.

but then this code worked. what is the difference in two given snippets for creating nested array such that field is not shown when no data is added?

const CollectionSchema = new Schema({
  field1: { type: [String], default: () => undefined},
});

Solution

  • With [{ type: String, default: undefined}] you create an array as a field1 which has string as an element. If there's no value, you will have undefined element in array. That is why it doesn't work.

    In other words, equivalent code for this will be:

    const CollectionSchema = new Schema({
      field1: [fieldSchema],
    });
    const fieldSchema = new Schema({
      field : { type: String, default: undefined},
    });
    

    As you can see, field1 won't be undefined.

    With { type: [String], default: () => undefined} you just create an array of strings. That is why it works.