Save and Actulize document arrays created dynamically

2

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();
    
asked by Wilfredo 16.11.2016 в 15:07
source

1 answer

1

You could use the dot notation to access the elements that are nested.

Update your registration:

Goals.findOneAndUpdate({userId: user.id}, {$set: {"yearsData.2016.sales": "12345678"}}, {upsert: true}).exec();

Create a new record:

Goals.findOneAndUpdate({userId: user.id}, {$set: {"yearsData.2017.sales": "123"}}, {upsert: true}).exec();
    
answered by 17.11.2016 в 07:38