10

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?

3 Answers 3

28

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

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

Comments

12

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:

Comments

2

It should be a json, I don't know what is what you posted there.

new Schema({ warning: { type: Array, default: [10, 50, 99] } })

1 Comment

Oh yeah,I thought it was dead, nobody talks about it anymore :)

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.