【发布时间】: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