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
user.find({ name: req.body.username })
is going to return an array. So in the code below, all those fields suchUser.name , User.username, User.email
etc are going to be undefined sinceUser = [{name:xxx,username:xxx }]
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()
.Instead of this
find({})
you can usefindOne({})
causefind({})
going to return an array but your are expecting an object that the the problemUse findOne() instead of find() method, find() method returns an array of objects and findOne() method return a single particular object.
and you can pass specific filed which you want to get like