skip to Main Content

I’m still new to reactjs and mongodb.I am trying to fetch a single record of user and display it on the page. But so far I got no output. I want the page to immediately display the result on load

This is my profile.js:

componentDidMount() {
    const user = localStorage.getItem('user')
    const userObject = {
        username: localStorage.getItem('user'),
    };
    axios.post('http://localhost:4000/users/getUser', userObject)
        .then((res) => {
            console.log("hi"+res.data)
            const userinfo = res.data
            
            this.setState({
                name: userinfo.name,
                username: res.username,
                email: res.email,
                password: res.password,
                company: res.company,
                position: res.position

            })
        })
        .catch(function (error) {
            console.log(error);
        })
}

and this is my backend(user.js):

let mongoose = require('mongoose'),
express = require('express'),
router = express.Router(),
user = require('../models/user-schema');

router.post('/getUser', async (req, res) => {
console.log(req.body.username)
const User = await user.find({ name: req.body.username })

if (!User) {
    return { status: 'error', error: 'Invalid Login' }
}else {
    return res.json({
        status: 'ok',
        name: User.name,
        username: User.username,
        email: User.email,
        company:User.company,
        position: User.position,
        level: User.userLevel
    })
}

})

3

Answers


  1. user.find({ name: req.body.username }) is going to return an array. So in the code below, all those fields such User.name , User.username, User.email etc are going to be undefined since User = [{name:xxx,username:xxx }]

    res.json({
            status: 'ok',
            name: User.name, // undefined
            username: User.username, // undefined
            email: User.email, // undefined
            company:User.company, // undefined
            position: User.position,// undefined
            level: User.userLevel // undefined
        })
    

    You should use user.findOne({ name: req.body.username }) which will return a single object and then you can access the properties.

    Additionally (Personal preference) , one might have multiple users with the same username. To make sure you’re retrieving the correct docuemnt, rather use findById().

    Login or Signup to reply.
  2. Instead of this find({}) you can use findOne({}) cause find({}) going to return an array but your are expecting an object that the the problem

    Login or Signup to reply.
  3. Use findOne() instead of find() method, find() method returns an array of objects and findOne() method return a single particular object.

    const User = await user.findOne({ name: req.body.username }) 
    

    and you can pass specific filed which you want to get like

    let User = await user.findOne({ name: req.body.username },{username:1, email:1, company:1, position:1, level:1});
    
    if(!User){
      return res.status(404).json({ status: 'error', error: 'Invalid Login' });
    } else {
      return res.status(404).json({status:"ok", ...User});
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search