Good morning, I am working with mongodb and mongoose, and I have the following problem. I have a collection that is made up of a field, which must be an array ( yearsData
that will be seen below) that will keep a record of other years, something like this (expected result):
{
"id":"123456",
"yearsData":{
"2015":{
"sales":"123456"
},
"2016":{
"sales":"1324"
}
}
}
Where yearsData will be saved every new year, the problem I have is that I am using this code:
if(typeof g === 'undefined' || g === null) {
goals.save(function(err, doc){
if (err) bro.debug('err ', err);
else
bro.debug('Survery Saved');
});
}
else{
Goals.findOneAndUpdate({userId: user.id},{$set:{ yearsData: JSON.stringify(dataHistorical)}}, {upsert: true, multi: false, new: true}).exec();
}
But when I emulate the following year, or the previous year (which are not in my collection), I update the record that I already have, in other words it does not save it in the array (yearsData) but it leaves me a single record. If I try with 2015 I get this:
{
"id":"123456",
"yearsData":{
"2015":{
"sales":"123456"
}
}
}
And if I try with 2016 I get this:
{
"id":"123456",
"yearsData":{
"2016":{
"sales":"1324"
}
}
}
Although I know that the problem is in the findOneAndUpdate
I do not know how to do it so that if the registry is updated and if it is not stored in the array yearsData
.
Edit I've also tried this update code:
Goals.findOneAndUpdate({userId: user.id}, { yearsData: JSON.stringify(dataHistorical)}, {upsert: true}).exec();