【发布时间】:2019-07-17 05:22:32
【问题描述】:
我是 mongoDB 和 mongoose 的新手。但是我想做的是能够通过他们的电子邮件访问我存储在数据库中的用户,如果成功检索到用户,我会将他们写的密码与存储在数据库中的哈希密码进行比较
这就是我的架构所拥有的
用户架构
var UserSchema = new Schema({
firstName: { type: String, required: true }, //require makes it so that the fields can't be left blank
lastName: {type: String, required: true},
emailAddress: {type: String, required: true},
password: {type: String, required: true}
});
var User = mongoose.model("User", UserSchema);
我在我的 routes.js 文件中使用 basic-auth 包以便在邮递员中测试这个 api,这是我卡住的部分,const user = User.find({' emailAddress': credentials.name, user.emailAddress} ); 我无法组合查询以访问数据库中的用户电子邮件
//This middle-where function will authenticate users
const authenticateUser = (req, res, next) => {
let message = null;
// Parse the user's credentials from the Authorization header.
const credentials = auth(req);
// If the user's credentials are available...
if (credentials) {
// Attempt to retrieve the user from the data store
// by their email (i.e. the user's "key"
// from the Authorization header).
const user = User.find({'emailAddress': credentials.name, user.emailAddress} );
// If a user was successfully retrieved from the data store...
if (user) {
// Use the bcryptjs npm package to compare the user's password
// (from the Authorization header) to the user's password
// that was retrieved from the data store.
const authenticated = bcryptjs
.compareSync(credentials.pass, user.password);
在这个快速路由器中,只有经过身份验证后,我才会返回用户
//GET /api/users 200, THIS WORKS IN POSTMAN
//This Route returns the currently authenticated user,
router.get('/users', authenticateUser, (req, res) => {
//within the route handler, the current authenticated user's information is retrieved from the Request object's currentUser property:
const user = req.currentUser;
//we use the Response object's json() method to return the current user's information formatted as JSON:
res.json({
firstName: user.firstName,
lastName: user.lastName,
});
});
有人可以帮忙吗?作为参考,这是我的回购https://github.com/SpaceXar20/rest_api-mongo-p9
【问题讨论】:
标签: database mongodb express mongoose