Abe Miessler
Abe Miessler

Reputation: 85056

Mongoose won't let me insert null value for Number?

I have the following Mongoose schema defined:

participantSchema = new Schema({
  id: Number,
  email: String,
  survey: {
    type: Schema.Types.ObjectId,
    ref: 'Survey'
  },
  created: {
    type: Date,
    "default": Date.now
  },
  answers: [
    {
      question: {
        type: Schema.Types.ObjectId,
        ref: 'Question'
      },
      values: Array,
      question_id: Number,
      sub_id: Number
    }
  ]
});

When I try to insert the following values for my answers array:

[{ question_id: 60800,
  _id: 52f53345f06cf301f2a38465,
  values: [ 'c2' ] }
{ question_id: 60801,
  sub_id: 19690,
  _id: 52f53345f06cf301f2a38464,
  values: [ 'C1' ] }
{ question_id: 60801,
  sub_id: 19691,
  _id: 52f53345f06cf301f2a38463,
  values: [ 'C3' ] }
{ question_id: 60802,
  _id: 52f53345f06cf301f2a38462,
  values: [ null ] }
{ question_id: 60803,
  sub_id: 19692,
  _id: 52f53345f06cf301f2a38461,
  values: [ null ] }]

It throws the error:

CastError: Cast to number failed for value "null" at path "sub_id"

If I hardcode all the sub_ids to either 1 or null it seems to work, but when there is a mix it throws the error. Any suggests for a work around?

Upvotes: 2

Views: 1619

Answers (1)

jwerre
jwerre

Reputation: 9584

Do this:

sub_id: {type: Number, sparse: true}

and check out this

Upvotes: 3

Related Questions