Mongoose不会让我为Number插入空值?

时间:2014-02-07 19:33:00

标签: node.js mongodb mongoose

我定义了以下Mongoose架构:

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
    }
  ]
});

当我尝试为answers数组插入以下值时:

[{ 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 ] }]

它抛出错误:

  

CastError:对于路径“sub_id”

的值“null”,转换为数字失败

如果我将所有sub_id s硬编码为1或null它似乎可以工作,但是当有混合时它会抛出错误。有什么建议可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

这样做:

sub_id: {type: Number, sparse: true}

并查看this