I'm saving a document into a mongodb collection and upon success im returning the document.
ie:
ProductHistory.findOneAndUpdate(
{productId: product._id},
$push: {'history': historyData },
{upsert: true, new: true})
.exec((err, success) => {
if (err){
console.log('Error: ', err)
}
console.log('success is: ', success)
}
The result is successfully saved entry and a console logged object which looks like the following:
{
_id: 616eb07b1e7edf6e9b035707,
history: [
{
_id: 61b7cdb160854a0564c15f25,
value: 114.5,
},
//...repeated objects x times
]
}
The problem is I want to access history so I can perform a forEach
on it but I'm having trouble selecting it.
If i do
console.log('success is:' , success.history)
it returns undefined.
Likewise if i do success.history.map()
. I've also tried destructing is using:
const {history} = success
I just can't seem to grab that array for some reason! any ideas please?
Thanks
CodePudding user response:
Without viewing your Mongoose schema, I can't say for certain. However, more than likely you haven't added the history
array type to your schema.
Solutions
- Add this array to your schema (preferred method).
- You should be able to bypass the schema by accessing
success._doc
object. This is not recommended and should only be used for testing and whatnot during development.