简体   繁体   English

使用节点js从mongodb获取数据

[英]fetch the data from the mongodb using node js

i have created a login program using node currently i am get only the token from jwt and but i need username ,_id & mobile number also with the token which is already stored in the database how to fetch this details. 我已经使用节点创建了一个登录程序,目前我只是从jwt获得令牌,但是我还需要用户名,_id和手机号码以及已存储在数据库中的令牌,以获取此详细信息。 please help me i am new to node and mongo 请帮助我,我是Node和Mongo的新手 在此处输入图片说明

-------Schema------------ -------模式------------

var mongoose = require('mongoose');

var users = new mongoose.Schema({
    _id: Number,
    username: String,
    mobile: Number,
    email: { type: String, required: true},
    password: { type: String, required: true},
});

module.exports = mongoose.model('users', users);

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');


const User = require('../models/users');
router.post('/login', (req, res, next) => {

  User.find({ email: req.body.email })
    .exec()
    .then(users => {
      if (users.length < 1) {
        return res.status(401).json({
          message: "This email does not exist please registor"
        });
      }

      console.log(users[0].password);
      bcrypt.compare(req.body.password, users[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth fail"
          });
        }
        console.log(result);
        if (result) {
          const token = jwt.sign({
            email: users[0].email,
            userId: users[0]._id
          }, process.env.JWT_KEY,
            {
              expiresIn: "1h"
            }
          );
          return res.status(200).json({
            message: 'login successfull',
            token: token
          });
        } else {
          res.status(401).json({
            message: "password is incorrect"
          });
        }
      });
    })
    .catch(err => {
      res.status(500).json({
        error: err
      });
    });
});
module.exports = router;

Please help me fetch username, id & mobile along with the token 请帮助我获取用户名,ID和手机以及令牌

Add those information while creating token. 在创建令牌时添加这些信息。

const token = jwt.sign({
        username: users[0].username,
        email: users[0].email,
        userId: users[0]._id,
        mobile: users[0].mobile
      }, process.env.JWT_KEY,
        {
          expiresIn: "1h"
        }
      );

Also you should use mongoose "findOne" instead of using "find" it will allow you to use user object like "user.email" rather than dealing with array and doing "users[0]". 另外,您应该使用猫鼬“ findOne”而不是“ find”,它将允许您使用诸如“ user.email”之类的用户对象,而不是处理数组并执行“ users [0]”。

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

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