node.js - Mongoose 不允许我为 Number 插入空值?

标签 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: Cast to number failed for value "null" at path "sub_id"

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

最佳答案

这样做:

sub_id: {type: Number, sparse: true}

并查看this

关于node.js - Mongoose 不允许我为 Number 插入空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21636282/

相关文章:

javascript - 如何更新全局对象

javascript - 使用 node.js 读取 express.js 中的参数的正确语法是什么

javascript - 类型错误 : resolver is not a function

javascript - 使用空子文档集合保存 Mongoose 文档会导致重复键错误

json - 将 JSON 查询字符串解析为 JSON 对象

node.js - 包 'cairo' , 'virtual:world' 需要,未找到

javascript - Express 中间件 : app. 使用和 app.all

java - 从文档中获取多个整数,将它们组合起来,除以值并从集合中获取顶部结果

MongoDB Compass $match 和 $text 结果为 "Expected "["or AggregationStage but "{"found."

node.js - 如何对 keystonejs 模型进行单元测试?