1

I have page where many users are displayed. When I click on a user, it directs to its page. I want that user to be displayed on this page, but I get an error: Cast to ObjectId failed for value "undefined" at path "_id" for model "user"

Some codes below.

server.js:

app.get('/api/getAnotherUser/:id', getAnotherUser);

getAnotherUser.js:

const User = require('../models/User');

exports.getAnotherUser = async (req, res) => {
    try {
        const user = await User.findById(req.params.id).select('-password');
        res.json(user);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
};

User schema:

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
    name: {
        type: String,
    }
});

module.exports = mongoose.model('user', UserSchema);

Path to this page:

<PrivateRoute path="/user/" component={User} />

This is where I map through all the users, key is _id, and when I click on the button OPEN, it will redirect that specific user's page:

return this.state.users.map((user) => (
            <div className="card" key={user._id}>
                <div className="image-container">
                    <img src={user.image} alt="" />
                </div>
                <div className="card-details">
                    <p>{user.name}</p>
                    <p>{user.age}</p>
                    <p>{user.gender}</p>
                    <p>{user.location}</p>
                </div>
                <Link to={`/user/${user._id}`}>
                    <Button>Open</Button>
                </Link>
            </div>
        ));

The page where I want the specific user to be displayed (by _id):

in my browser: http://localhost:3000/user/5ed9d49c7e516616600eb693

in Postman I successfully get the user by _id: http://localhost:5000/api/getAnotherUser/5ed9d49c7e516616600eb693

MongoDB: "_id": "5ed9d49c7e516616600eb693"

export class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: ''
        };
    }

    componentDidMount() {
        const token = localStorage.getItem('token');
        if (token) {
            this.setState({ loading: true });
            axios.get(`/api/getAnotherUser/${this.props._id}`, { headers: { 'X-Auth-Token': token } }).then((res) =>
                this.setState({
                    name: res.data.name,
                })
            );
        }
    }

    render() {
        return (
            <div>
                <h1>user: {this.state.name}</h1>
            </div>
        );
    }
}

And this is where I get the error. That specific user by _id is not displayed. What went wrong here? In Postman, with the get request, I can fetch that user by _id, but in my application I must have forgotten something. Could anyone please point it out where? Thanks!

David
  • 321
  • 10
  • 23
  • According to [THIS](https://stackoverflow.com/questions/45598854/passing-values-through-react-router-v4-link) I could solve it! – David Jun 06 '20 at 02:37

1 Answers1

2

It says this.props._id is undefined, so what you have to do is

componentDidMount() {
        const token = localStorage.getItem('token');
        console.log(this.props._id) //check if this is undefined
        if (token && this.props._id) {
            ...
        }
    }

If this.props._id logged as undefined in your browser console then you have to pass the _id from the parent component if it is not undefined in the parent

onuriltan
  • 3,730
  • 4
  • 25
  • 37
  • Yes, you were right. Here is the complete solution: https://stackoverflow.com/questions/45598854/passing-values-through-react-router-v4-link – David Jun 06 '20 at 02:37