Dastan
Dastan

Reputation: 2106

How to find an object inside an array inside a mongoose model?

I'm trying to query an object that's inside an item which is inside a mongoose model, when I'm trying to find that object with the find() method or _.find() method, I can't get access to the object for some reason and when I console.log() it, it gives me undefined or when I use array.filter() it gives me an empty array, which means the object that I'm trying to access does not meet the criteria that I give it in the lodash find method, but then when I look at my database I see that the object does actually have the properties to meet the criteria. So I don't know what I'm doing wrong, here's my code: as you can see I'm trying to get the information of the item that the user clicked on and want to see:

router.get("/:category/:itemId", (req, res) => {
    console.log(req.params.itemId);
    //gives the item id that the user clicked on
    console.log(req.params.category);
    //gives the name of category so I can find items inside it
    Category.findOne({ name: req.params.category }, (err, category) => {
      const items = category.items; //the array of items
      console.log(items); //gives an array back
      const item = _.find(items, { _id: req.params.itemId });
      console.log(item); //gives the value of 'undefined' for whatever reason
    });
  });

The category Schema:

const catSchema = new mongoose.Schema({
  name: {
    type: String,
    default: "Unlisted",
  },
  items: [
    {
      name: String,
      price: Number,
      description: String,
      img: String,
      dateAdded: Date,
      lastUpdated: Date,
    },
  ],
  dateCreated: Date,
  lastUpdate: Date,
});

Upvotes: 5

Views: 2239

Answers (2)

Yad Hersh
Yad Hersh

Reputation: 34

well the answer is a little bit obvious, you are using MongoDB and in Mongo you have "_ID" you can use that "_ID" only with Mongoose! so you just have to remove the underscore and that is it! do it like this const item = _.find(items, { id: req.params.itemId });

Upvotes: 1

pacy.eth
pacy.eth

Reputation: 176

hope you are doing better. When I look at your Schema I see that the item field is an array of objects which doesn't have an _id inside so when you create a new instance of catShema it just generates an _id field for the new instance but not for each item inside the items array, just also enter the id of the item in question because according to my understanding, you must also have a model called items in your database When you save these records in your database, you will generate an element with this structure

{
    _id: String, // auto generated
    name: String,
    items: [ {"name1", "price1", "description1", "imgUrl1", "dateAdded1", "lastUpdated1"},{"name2", "price2", "description2", "imgUrl2", "dateAdded1", "lastUpdated2"}, ...],
    dateCreated: Date,
    lastUpdate: Date
} 

Note : the code provided at the top is only an illustration of the object which will be registered in the database and not a valid code

Here you can notice that there is not a field called _id in the object sent inside the database. My suggestion to solve this issue is

  • To create an additional field inside the items array called _id like :

    { ..., items: [ { _id: { type: String, unique : true, required: true // to make sure you will always have it when you create a new instance }, ... ... // the rest of fields of items
    }, ...

Now when you create a new instance make sure in the object you enter in the database the _id is recorded when you call the catInstance.save() so inside the catInstance object you have to add the current Id of the element to be able to filter using this field. Hope my answer helped, if you have any additional questions, please let me know Happy coding ...

Upvotes: 1

Related Questions