Node.js 基于参数查找单个用户

Node.js 基于参数查找单个用户,node.js,angular,mongodb,mean-stack,bcrypt,Node.js,Angular,Mongodb,Mean Stack,Bcrypt,我正在尝试设置登录到我正在工作的网站。我很难根据用户的登录信息找到用户,因为我的结果总是为空 这是我的用户服务中传递用户名和密码的内容 confirmUser(username: string, password: string) { this.http.get<{ confirmUser: ConfirmUser }>('http://localhost:3000/users?username=' + username.toLowerCase() + '&pass

我正在尝试设置登录到我正在工作的网站。我很难根据用户的登录信息找到用户,因为我的结果总是为空

这是我的用户服务中传递用户名和密码的内容

confirmUser(username: string, password: string) { 
    this.http.get<{ confirmUser: ConfirmUser }>('http://localhost:3000/users?username=' + username.toLowerCase() + '&password=' + password).subscribe(
        // success function
        (response) => {
           console.log(response);
           return; //Only returning here just to check the response before moving on while I debug
           // this.user = response.user;
           // console.log(this.user);
        }
     ),
     (error: any) => {
        console.log(error);
     } 
}
当我尝试根据用户的用户名筛选它以查找用户,然后根据传入的密码创建的新哈希检查存储的哈希时,就会出现问题。以下是我尝试过的一个例子:

router.get('/', (req, res, next) => {
const hash = bcrypt.hashSync(req.query.password, saltRounds); //Hash the password argument
User.findOne( { username: req.username }).then(user => { //Find based on username

    if (user){ //Check here to match the hashes before returning?
        res.status(200).json({
            confirmUser: ConfirmUser = {
                id: user.id,
                username: user.username    
            }
        });

    } else {
        res.status(401);
    }

})
.catch(error => {
    // returnError(res, error);
});
});
首先,我不完全确定在哪里比较这两个散列以确保我获取的是正确的用户,而不是只有相同用户名的用户(尽管我想确保用户名是唯一的可以解决这个问题)

我知道有一种方法可以只返回找到的记录中的特定字段,我相信可以添加一些类似于
{username:1,password:0}
的内容,但我也不确定如何实际执行此操作。理想情况下,我希望找到与用户名/密码匹配的用户,然后只返回要存储的用户ID和用户名以实际登录。完整的用户模型如下所示:

export class User {
constructor(
    public id: string,
    public firstName: string,
    public lastName: string,
    public username: string,
    public email: string,
    public password: string
) { }
}
confirmUser对象是仅包含以下字段的视图模型:

export class ConfirmUser {
constructor(
    public id: string,
    public username: string,
) { }
}

这可能是一个太多的问题,但我不想遗漏任何可能有助于解决问题的内容,因为我知道我可能有几个问题需要在这里解决,但我自己也不知道该怎么办。

这是因为您已经写信给我了。 findOne({username:req.username})。然后(user=>{//Find-based-username

可以看出,您错误地使用了未定义的req.username。 结果,用户为null

因此,请使用req.query.username或req.body.username


基于路线类型

非常感谢!有时只需要第二双眼睛。现在一切都正常了
export class ConfirmUser {
constructor(
    public id: string,
    public username: string,
) { }
}