【问题标题】:Moongoose require:true does not seem to work? [duplicate]Mongoose required:true 似乎不起作用? [复制]
【发布时间】:2017-01-03 03:05:11
【问题描述】:

我有以下 Mongoose 架构。

var ContactSchema = new Schema({
  name: { type: String, required: true },
  company: { type: String, required: true },
  email: { type: String, required: true },
  phone: { type: String, required: true }
},{ versionKey: false });

当我创建联系人帖子时,通过

var contact = new Model(req.body);
contact.save( function( err, result ) {
  if( err ) {
    res.status(422).json( err );
  }
  else {
    res.status(200).json( result );
  }
})

并且不提交所有字段,我收到错误 422。 required: true 有效。

但是,当我通过

更新现有联系人时
Model.findByIdAndUpdate(req.params.id, req.body, {new:true, select:    defaultProjection}, function( err, contact ){

if( err ) {
  res.status(422).json( err );
}
else {
  res.status(200).json( contact );
}

});

如果我离开,我不会收到任何错误,例如,email 为空。

我做错了什么? :-)

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你需要在updateuse $set

    试试这个:

    Model.findByIdAndUpdate(req.params.id, {'$set' : req.body}, 
        {new:true, select: defaultProjection}, function( err, contact ){
    
    if( err ) {
      res.status(422).json( err );
    }
    else {
      res.status(200).json( contact );
    }
    

    【讨论】:

    • 它没有用。它接受一个空字段。
    • 如果我添加了 runValidators: true,它确实有效。我不知道如何回答我自己的问题,这可能与有人将此标记为重复问题有关。我不知道。
    • 你可以给出你自己的答案。不是让你回答吗?而且,如果我的回答对您有帮助,您可以将其标记为已接受。
    猜你喜欢
    • 2019-03-20
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    相关资源
    最近更新 更多