I am trying to update a given subdocument inside an array using its id but when i use the vanila javascript array.find() i get undefined. below is the code
let offers = service.offers
console.log("OFFERS ARE ==========", offers)
const offerIDObject = mongoose.Types.ObjectId(offerID)
console.log("CONVERTED ID IS ==========", offerIDObject)
// Find returns undefined for some reason
const offer = offers.find((el) => {
return el._id === offerIDObject
})
offers.map((el, i) =>console.log("ARE OF SAME TYPES======", typeof(el._id) === typeof(offerIDObject)))
console.log("THE FOUND OFFER IS=======",offer)
What could be the problem with the find method?
CodePudding user response:
objectIds are never the same. you can convert it to string, then compare them like this: return el._id.toString() === offerIDObject.toString()
or use mongoose .equals() method:
const offer = offers.find((el) => {
return el._id.equals(offerIDObject)
})
both should work.