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

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


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 });


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 databaseWhen 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 knowHappy coding ...