Node.js 在Mongoose中将字段设置为空时出错

Node.js 在Mongoose中将字段设置为空时出错,node.js,mongoose,Node.js,Mongoose,我用的是猫鼬。我得到的错误如下: { 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.paren

我用的是猫鼬。我得到的错误如下:

{ 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}
})
我的代码是:

.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得到的父字段值不是ObjectId

此外,所有属性都是在MongooseJs模型上定义的,不会被取消定义

您需要将其设置为空:


这将清除该值

老问题,但我得到了同样的问题,我想分享答案。在创建类别对象之前,如果未使用有效值设置父属性,则必须手动从req.body中删除该父属性:

if (req.body.parent == "")
  delete req.body.parent; // or req.body.parent = null;
var category = new Category(req.body);

之后将其设置为null将不起作用-不要问我为什么。

你能发布你的代码吗?我添加了@EmilCondrea请检查。类别的代码是什么?req.body可能未定义空值:在架构定义中为true?该字段可为空。body中有什么?ObjectId作为父对象是否有一些内容,但它不会强制执行?抱歉,我无法理解您的问题。父项应为null或未定义。它没有父属性。是否设置了父属性?帖子的主体看起来像什么?
if (req.body.parent == "")
  delete req.body.parent; // or req.body.parent = null;
var category = new Category(req.body);