Я хотел бы иметь возможность читать список зарегистрированных пользователей с сервера БД Mean Stack Mongo и отображать его в моем веб-приложении.
До сих пор у меня был доступ только к этому списку,который зашифрован через терминал с помощью оболочки Mongo.
Есть идеи?Это фрагмент кода, в котором следует реализовать getUsers, но мои попытки getUsers пока не увенчались успехом.
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/user");
exports.createUser = (req, res, next) => {
bcrypt.hash(req.body.password, 10).then(hash => {
const user = new User({
email: req.body.email,
password: hash
});
if(req.body.adminCode === "secretCode123") {
newUser.isAdmin === true;
}
user
.save()
.then(result => {
res.status(201).json({
message: "User created!",
result: result
});
})
.catch(err => {
res.status(500).json({
message: "Invalid authentication credentials!"
});
});
});
};
// Here we create the token
exports.userLogin = (req, res, next) => {
let fetchedUser; // Otherwise user would only exist in the first then block
User.findOne({ email: req.body.email })
.then(user => {
if (!user) {
return res.status(401).json({
message: "Authentication failed"
});
}
fetchedUser = user;
console.log("The fetched user is " + fetchedUser);
console.log("The user is " + user);
console.log("The encrypted req.body.password is " + req.body.password);
console.log("The user.password is " + user.password);
return bcrypt.compare(req.body.password, user.password);
})
.then(result => {
console.log("The result is " + result); // It is either false or true
if (!result) {
return res.status(401).json({
message: "Authentication failed" // "Return" prevents execution of next part of code
});
}
const token = jwt.sign(
{ email: fetchedUser.email, userId: fetchedUser._id },
process.env.JWT_KEY,
{ expiresIn: "1h" }
);
res.status(200).json({
token: token, // No need to return because no code afterwards
expiresIn: 3600,
userId: fetchedUser._id
});
console.log("The token is " + token)
})
.catch(err => {
return res.status(401).json({
message: "invalid authentication credentials!"
});
});
};
/* exports.getUsers = (req, res, next) => {
const listofUsers = [
{ id: 12, email: "Narco@test.com" },
{ id: 13, email: "Bombasto@test.com" },
{ id: 14, email: "Celeritas@test.com" },
{ id: 15, email: "Magneta@test.com" },
{ id: 16, email: "RubberMan@test.com" },
{ id: 17, email: "Dynama@test.com" },
{ id: 19, email: "Magma@test.com" },
{ id: 20, email: "Tornado@test.com" }
];
res.status(200).json({
message: "Dummy User ID fetched from the server",
admin: listofUsers
})
} */
exports.getUsers = (req, res, next) => {
const userQuery = User.find();
let fetchedUsers;
userQuery
.then(userDocuments => {
const token = jwt.sign(
{ email: fetchedUser.email, userId: fetchedUser._id },
process.env.JWT_KEY,
{ expiresIn: "1h" }
);
res.status(200).json({
token: token, // No need to return because no code afterwards
expiresIn: 3600,
userId: fetchedUser._id
});
console.log("The token is " + token)
fetchedUsers = userDocuments;
console.log("The fetchedUsers are: "+ fetchedUsers);
return User.count();
})
.then(count => {
res.status(200).json({
message: "Users fetched successfully!",
users: fetchedUsers,
maxUsers: count
});
console.log(fetchedUsers);
})
.catch(error => {
res.status(500).json({
message: "Fetching users failed!"
});
});
}
Спасибо, GB