I'm having trouble with my code. It's very simple, but i don't know why it's not returning the object with the ID. All I'm getting is the error above.
I followed another instruction that is identical to mine, but still.
How can I return the object matching the ID in the URL?
My code:
const app = express();
// const { PORT = 3000 } = process.env;
app.listen(3000);
app.get('/', (req, res) => {
res.status(200).send('oh noes uwu :)');
});
app.get('/users', (req, res) => {
res.send(users);
});
app.get('/cards', (req, res) => {
res.send(cards);
});
app.get('/users/:_id', (req, res) => {
const { name } = users[req.params._id];
res.send(name);
});
const users = [
{
name: 'Ada Lovelace',
about: 'Mathematician, writer',
avatar: 'https://www.biography.com/.image/t_share/MTE4MDAzNDEwODQwOTQ2MTkw/ada-lovelace-20825279-1-402.jpg',
_id: 'dbfe53c3c4d568240378b0c6',
},
{
name: 'Tim Berners-Lee',
about: 'Inventor, scientist',
avatar: 'https://media.wired.com/photos/5c86f3dd67bf5c2d3c382474/4:3/w_2400,h_1800,c_limit/TBL-RTX6HE9J-(1).jpg',
_id: 'd285e3dceed844f902650f40',
},
{
name: 'Alan Kay',
about: 'Computer scientist',
avatar: 'https://cdn.cultofmac.com/wp-content/uploads/2013/04/AlanKay.jpg',
_id: '7d8c010a1c97ca2654997a95',
},
{
name: 'Alan Turing',
about: 'Mathematician, cryptanalyst',
avatar: 'https://cdn.britannica.com/81/191581-050-8C0A8CD3/Alan-Turing.jpg',
_id: 'f20c9c560aa652a72cba323f',
},
{
name: 'Bret Victor',
about: 'Designer, engineer',
avatar: 'https://postlight.com/wp-content/uploads/2018/03/109TC-e1535047852633.jpg',
_id: '8340d0ec33270a25f2413b69',
},
{
name: 'Douglas Engelbart',
about: 'Engineer, inventor',
avatar: 'https://images.fineartamerica.com/images-medium-large-5/douglas-engelbart-emilio-segre-visual-archivesamerican-institute-of-physics.jpg',
_id: '3c8c16ee9b1f89a2f8b5e4b2',
},
];
When you write users[req.params._id], you're trying to access an object at a certain index of an array. Right now, if the URL parameter is dbfe53c3c4d568240378b0c6, basically this is how it reads:
What you can do is to iterate over users, such as:
let userName;
for (let user of users) {
if (user._id === req.params._id) userName = user.name;
}