Я занимаюсь разработкой веб-приложения с использованием стека MEAN с Angular 6. Там у меня есть форма для отправки «значения высоты».Я хочу отправить его с электронной почтой зарегистрированного пользователя.У меня есть отдельная схема для пользователя.Ниже приведена схема моего роста.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// Schema for height panel
var heightSchema = new mongoose.Schema({
userName: {
type: Schema.ObjectId,
ref: 'user'
},
height: {
type: Number
},
});
module.exports = mongoose.model('heightValue', heightSchema);
Ниже приведен маршрут моего сообщения.
//post height values
router.post("/save", function (req, res) {
var mod = new height(req.body,{userName : req.body["user.email"]});
height.findOneAndUpdate(
{
userName: req.user.email,
height: req.body.height,
},
req.body,
{ upsert: true, new: true },
function (err, data) {
if (err) {
console.log(err);
res.send(err);
} else {
console.log(res);
res.send(mod);
}
}
);
});
Что я пробовал,
Я пробовал это.
userName: req.user.email,
Но я не могу получить идентификатор пользователя зарегистрированного пользователя.Ответ показывает ошибку «Неожиданный конец ввода».Как я могу достичь своего требования.Попробовав так много методов, наконец-то обновили маршруты и схему.Но проблема все та же.Кто-нибудь может определить, где я ошибся?
- ОБНОВЛЕНО -
Здесь я возвращаю токен.
passport.use('login', new localStrategy({
usernameField : 'email',
passwordField : 'password'
}, async (email, password, done) => {
try {
//Find the user associated with the email provided by the user
const user = await UserModel.findOne({ email });
if( !user || user.status === false){
//If the user isn't found in the database, return a message
return done(null, false, { message : 'User not found'});
}
//Validate password and make sure it matches with the corresponding hash stored in the database
//If the passwords match, it returns a value of true.
const validate = await user.isValidPassword(password);
if( !validate ){
return done(null, false, { message : 'Wrong Password'});
}
//Send the user information to the next middleware
return done(null, user, { message : 'Logged in Successfully'});
} catch (error) {
return done(error);
}
}));
passport.use(new JWTstrategy({
//secret we used to sign our JWT
secretOrKey : 'top_secret',
//we expect the user to send the token as a query paramater with the name 'secret_token'
jwtFromRequest : ExtractJWT.fromUrlQueryParameter('secret_token')
}, async (token, done) => {
try {
//Pass the user details to the next middleware
return done(null, token.user);
} catch (error) {
done(error);
}
}));
class Service
{
constructor()
{
}
/**
*
* @param {type} req
* @param {type} res
* @param {type} next
* @returns {undefined}
* Authenticate functionality.
*/
async authenticate(req,res,next)
{
passport.authenticate('login', async (err, user, info) => {
try {
if(err || !user){
const error = new Error('An Error occured');
return next(error);
}
req.login(user, { session : false }, async (error) => {
if( error ) return next(error);
const token = this.getJWT(user);
return res.json({ token });
});
} catch (error) {
return next(error);
}
})(req, res, next);
}
/**
*
* @param {type} user
* @returns {Service.getJWT.token}
* Create JWT token.
*/
getJWT(user)
{
//We don't want to store the sensitive information such as the
//user password in the token so we pick only the email and first name
const body = { email : user.email , firstName : user.firstName};
// Token will be expired in 24 hours.
const token = jwt.sign({ user : body },'top_secret',
{
expiresIn : '24h'
});
return token;
}
}
module.exports = Service;