How do I access the value of the objects inside of the 'items' property
[
{
_id: 61b6fb289ef81937305ea137,
name: 'Apples',
user: 61b5d787aa22ab26e3f8d0bb,
items: [ [Object], [Object], [Object], [Object], [Object] ],
__v: 5
}
]
This is the code I wrote inside a get route that allowed me to get to where I am now. I just need to be able to get ahold of the value within the items
property.
const custom = _.capitalize(req.params.customList);
const list = await List.find({name:custom, user:{$eq: req.user._id}});
Edit:
Thank you all for your help. After some more digging, trial and error, a nap, and some Lo-fi music I figured out the issue and how to fix it. The reason why I wanted to access the item in the array was so that I can iterate through the contents and present it on the from end. The main issue I was having was that every time I saved an item into a list it would not appear in the wrong list in both the DB and the front end.
I spent a majority of my time believing that this code was the issue
router.get('/:customList', auth, async(req, res)=>{
const custom = _.capitalize(req.params.customList);
const list = await List.findOne({name:custom, user:{$eq: req.user._id}});
if(!list)
{
const newList = new List({
name:custom,
user:req.user._id,
});
newList.save();
res.redirect('/'+custom)
}
else{
res.render('home',{
listTitle:custom, newListItems: list.items
})
}
});
But in actuality, it was this one
router.post("/home", auth, async(req, res)=>{
const {newItem, list} = req.body;
const item = new Item({
name: newItem,
user: req.user._id
});
if(list === req.user.username){
item.save();
res.redirect('/home');
}else{
// The was causing the issue
const result = await List.findOne({name:list})
result.items.push(item);
result.save();
res.redirect('/'+list);
}
});
const result = await List.findOne({name:list})
would find the first list that matches and add the item into the array even though they could be multiple list names that matched.
I fixed it with this const result = await List.findOne({name:list, user:{$eq:req.user._id});
. This took me three days to figure out and I'm just excited to finally figure it out. Sorry for the long post.