1
   {
       'ID': 'IDexample',
       'Coordinates'  : [
           {'CoordinateX' :  123,
            'CoordinateY':  5
           },
           {'CoordinateX' :  54,
            'CoordinateY':  23'
           }
        ]
    }

How can I add 2 elements to array Coordinates if "IDexample" is present in coordinatesCollection ? If not exist add new Document' to collection. I am using MongoClient and the name of the collection is coordinatesCollection.

 coordinatesCollection.findOne( { "unique_id" : unique_id }, function(err, object){
    if (object) {
      ????
    } else {
      coordinatesCollection.insert({
        "unique_id" : unique_id,
        "coordinates" : [
          {"coordinateX" :msg.coordinatex,
           "coordinateY" : msg.coordinatey
          }
        ]
      })
    }
  });
lolix
  • 1,447
  • 2
  • 19
  • 23

1 Answers1

0

Try this:

   coordinatesCollection.findOne( { "unique_id" : unique_id }, function(err, object){
        if (object) {
         coordinatesCollection.findOneAndUpdate({ "unique_id" : unique_id },
       { $push: {"Coordinates": {$each: [ { "CoordinateX": 5, "CoordinateY": 8 }, { "CoordinateX": 6, "CoordinateY": 7 } ]}}},function(err,data){
             if(err){
                console.log("err:"+err);
             }
             else if(data){
                console.log("UPDATED:"+data);
             }

       });
        } else {
          coordinatesCollection.insert({
            "unique_id" : unique_id,
            "coordinates" : [
              {"coordinateX" :msg.coordinatex,
               "coordinateY" : msg.coordinatey
              }
            ]
          })
        }
      });
Shantanu Madane
  • 617
  • 5
  • 14