简体   繁体   English

不带参数查询时的猫鼬(mongodb)怪异行为

[英]mongoose (mongodb) weird behaviour when querying with no params

I'm using Postman to post to my backend to get a user based on his username and password. 我正在使用Postman发布到我的后端,以便根据用户名和密码获得用户。

Whenever the username doesn't exist as a field in the form, a user is still returned (I only have one user at the moment and he is returned); 每当用户名不存在于表单中的字段中时,仍然会返回一个用户(我目前只有一个用户,并且已经返回了他);

But, if I add the username field, it returns null unless it is the correct username, even if its empty. 但是,如果我添加了用户名字段,则除非它是正确的用户名,否则即使它为空,它也将返回null。

this is the code: 这是代码:

 User.findOne({
    username: req.body.username
  }, function(err, user) {
    if(err) throw err;

    // prints null if username field is present and incorrect even if its empty
    // prints a user as json if the username field is not present
    console.log(user); 
    if(!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    }

I am still checking for a password so it won't work for someone to post without a username field but it is very odd and prevents the right error message to display. 我仍在检查密码,因此对于没有用户名字段的人来说,它将不起作用,但是它很奇怪,并且会阻止显示正确的错误消息。 Why does this happen? 为什么会这样?

You have to check first if the parameter exists, or req.body.username will equal undefined which will result in an empty query. 您必须首先检查参数是否存在,否则req.body.username将等于undefined ,这将导致空查询。

findOne with an empty query will fetch the first document found, as you can get all the documents with find with an empty query. 查询为空的findOne将获取找到的第一个文档,因为您可以使用查询为空的find获取所有文档。

An empty string won't result as an empty query which is why you get null (you don't have any user with '' as username). 空字符串不会导致查询为空,这就是为什么您会得到null (您没有用户使用''作为用户名)。

TLDR: Check the presence of every parameter before building the query and return some 409 MissingParameterError if you are building a REST api. TLDR:构建查询之前,请检查每个参数的存在,如果正在构建REST api,则返回409 MissingParameterError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM