I want to access the name property. I tried doing the following but it returned undefined
:
Category.find()
.select("-_id")
.select("-__v")
.then((categories) => {
let creator = req.userId;
console.log(categories.name) //undefined
if (categories.creator === creator && categories.name === categoryName) {
note
.save()
this is console.log(categories)
:
[
{ name: 'test11', creator: new ObjectId("6359766eaf27f731e789f061") },
{ name: 'test11', creator: new ObjectId("6359766eaf27f731e789f061") },
{ name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
{ name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
{ name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
{ name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
{ name: 'categ1', creator: new ObjectId("635a316453d25ea50a3a4c5c") },
{
name: 'newCategName',
creator: new ObjectId("635a316453d25ea50a3a4c5c")
}
]
I want to check that if the current signed in user’s ID and the document name match an exact pair in the Category schema
2
Answers
Categories here is an array of objects, which contain name and ObjectId.
So just loop over the array and get what you want.
In the code I see you do this:
Try:
Since categories returned is a list of objects and not a single object. You can use
Array.find()
to filter your condition.Although a better and efficient approach based on the use case could be to directly use the filter condition in the query itself rather than fetching all categories and then filtering.
Used
findOne()
and second param projection to get the matching category.