Home > Net >  How can I access the "name" and "ObjectId" from this array of Objects? (Mongoose
How can I access the "name" and "ObjectId" from this array of Objects? (Mongoose

Time:10-27

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

CodePudding user response:

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:

console.log(categories.name)

Try:

console.log(categories[0].name)

CodePudding user response:

Since categories returned is a list of objects and not a single object. You can use Array.find() to filter your condition.

var 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"),
  },
];

const found = categories.find(
  (doc) => doc.creator === creator && doc.name === categoryName
);

if (found) {
  // rest of the code
}

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.

const creator = req.userId;
const categoryName = "ABC";
const result = await Category.findOne(
  { creator: creator, name: categoryName },
  "-_id -__v"
).exec();

if (result) {
  // rest fo the code
}

Used findOne() and second param projection to get the matching category.

  • Related