【问题标题】:Mongoose sends existing document when validation failed验证失败时,Mongoose 发送现有文档
【发布时间】:2018-01-22 23:53:16
【问题描述】:

我有一个创建文档的 POST 请求。我的问题是,当验证失败时,猫鼬将原始文档设置为响应的一部分。我想让猫鼬不发送现有文件,主要是散列密码。

这是回复

{
"code": 11000,
"index": 0,
"errmsg": "E11000 duplicate key error collection: ole.tournament index: name_1 dup key: { : \"First tournament\" }",
"op": {
    "name": "First tournament",
    "tournType": "single elimination",
    "seriesType": "bo1",
    "password": "$2a$10$xhA5UkpK.xH4QROdHf/Os.djs9CcU3C8PPcM8j99RocYPHS3x0tIC",
    "_creator": "5992734ebaa773270898e248",
    "_id": "59927361baa773270898e24a",
    "participants": [],
    "startedDate": null,
    "createdDate": "2017-08-15T04:06:57.640Z",
    "__v": 0
}
}

这是我添加的一些代码,因此 mongoose 不会发送密码,但它仅在创建或更新文档时有效,但在路径验证失败时无效:

TournamentSchema.methods.toJSON = function(){
  var tournament = this;
  var tournamentObject = tournament.toObject();
  return _.omit(tournamentObject, "password");
}

这是我的路线

.post('/add', authenticate, (req, res) => {
  req.body._creator = req.user._id;
  tournament = new Tournament(req.body);
  tournament.save().then((tournDoc) =>{
    res.status(200).send(tournDoc);
  }).catch((e) => {
    res.status(400).send(e);
  })
})

我知道解决此问题的快速方法是在 catch 块中省略它,但是有没有猫鼬方法可以做到这一点?

谢谢。

【问题讨论】:

  • 您可以随时操纵您发送的响应,创建一个白名单对象。

标签: node.js mongodb validation express mongoose


【解决方案1】:

您只需将errmsg 即错误消息发送回客户端。向客户端发送完整的错误对象不是一个好习惯。你可以看看下面的代码:

.post('/add', authenticate, (req, res) => {
   req.body._creator = req.user._id;
   tournament = new Tournament(req.body);
   tournament.save().then((tournDoc) =>{
      res.status(200).send(tournDoc);
   }).catch((e) => {
      res.status(400).send(e.errmsg);
   })
}) 

或者您甚至可以向客户端发送自定义错误消息,如下所示:

.post('/add', authenticate, (req, res) => {
   req.body._creator = req.user._id;
   tournament = new Tournament(req.body);
   tournament.save().then((tournDoc) =>{
      res.status(200).send(tournDoc);
   }).catch((e) => {
      if(e.code == 11000) {
         res.status(409).send("Validation failed!!");
      }
      res.status(500).send("Error occurred!! Please try again.");
   })
}) 

【讨论】:

  • 是的,这就是我认为我必须做的。我虽然可以选择避免这种猫鼬的行为。谢谢。
猜你喜欢
  • 2019-12-09
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 2019-05-04
  • 2021-06-30
  • 2020-03-16
  • 2014-11-19
相关资源
最近更新 更多