Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values in array mongoose

I am trying to make default values for array in mogoose schema:

warning:
 type: Array
 default: [10, 50, 99]

Am I right in such decision or there is some other way to do this?

like image 548
Jesus_Maria Avatar asked Jan 27 '16 09:01

Jesus_Maria


2 Answers

Regarding to the Mongoose-Documentation, your way is correct.

Here a small example:

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': [1, 2, 3]
    }
});

And a link to the related documentation page: http://mongoosejs.com/docs/2.7.x/docs/defaults.html

like image 196
Mijago Avatar answered Sep 19 '22 17:09

Mijago


for Mongoose v5.x

If you want to specify the type of the array child, you can define it like example below:

const BlogSchema = new Schema({
  tags: {
    type: [String],
    default: ["tech", "economy"],
  },
})

or

const BlogSchema = new Schema({
  tags: {
    type: [
      {
        type: String,
        // Another properties
      },
    ],
    default: ["tech", "economy"],
  },
})

References:

  • https://mongoosejs.com/docs/schematypes.html#arrays
like image 39
Laode Muhammad Al Fatih Avatar answered Sep 17 '22 17:09

Laode Muhammad Al Fatih