node.js - 在 Mongoose 中将字段设置为 null 时出错

标签 node.js mongoose

我正在使用 MongooseJS。我收到以下错误:

{ message: 'Cast to ObjectId failed for value "" at path "parent"',
  name: 'CastError',
  type: 'ObjectId',
  value: '',
  path: 'parent'
}

我不想为此对象设置父对象。我哪里错了?我该怎么办?

更新:

var category = new Category(req.body)
if(typeof category.parent === 'undefined'){
    category.parent=undefined;
}

类别架构是:

var CategorySchema = new Schema({
  name: {
    tr: {type : String, default : '', trim : true},
    en: {type : String, default : '', trim : true}
  },
  description: {
    tr: {type : String, default : '', trim : true},
    en: {type : String, default : '', trim : true}
  },
  subcategories:[{type : Schema.ObjectId, ref : 'Category', null: true}],
  parent: {type : Schema.ObjectId, ref : 'Category', null: true},
  products:[{type : Schema.ObjectId, ref : 'Product'}],
  images : [String],
  order: {type : Number, default: 0},
  createdAt  : {type : Date, default : Date.now},
  locale: {type : String, null: false}
})

我的 Jade 码是:

.controls
        select#parent(name="parent")
          option(value="") Select
          each cat in categories
            - if (category.subcategories.map(function(e) { return e.id; }).indexOf(cat.id) != -1)
                option(value=cat.id, selected) #{cat.name.tr}
            - else
                option(value=cat.id) #{cat.name.tr}

因此,如果用户不选择父级,则会将“”发送到服务器,并且服务器会给出该错误。

最佳答案

该错误表明您无法将尝试设置的类型转换为 category.parent 属性,因为它需要 ObjectId。我希望通过 req.body 传入的 parent 字段值不是 ObjectId

此外,所有属性都是在 MongooseJs 模型上定义的,并且不会未定义

您需要将其设置为null:

category.parent = null;

这将清除该值。

关于node.js - 在 Mongoose 中将字段设置为 null 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19810845/

相关文章:

javascript - Npm 未满足对等依赖项

用于 MonetDB 的 Node.js 和 ODBC

node.js - Elasticsearch SQL 查询不可能

node.js - 用于保存任何数据的 Mongodb 动态模式

node.js - Mongoose 查询检查搜索元素数组中的特定值

node.js - 在 mongodb 中读取然后更新的最佳方法是什么?

node.js - Node : Static imports possible?

javascript - 如何过滤MongoDB集合文档的数组

javascript - nodejs查询数据和代码组织

javascript - 无法使用 node.js 根据 MongoDB 中的特定字符串对值进行分组?