Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push Multiple Values into mongodb array using nodeJS

I have one mongodb schema (ChampionshipSchema) that accepts a multiple values :

tieBreak: [{
  name: String,
  priority : Number
}],

If I add one by one in this schema, it is OK, but if I try to add a list do values at the same time, I have an error.

Code to add in the schema :

function createTable (idChampionship, tieBreaks, callback) {
  // tieBreaks is an array of tieBreak values
  var query = { _id : idChampionship };

  var newValues = {
    $push: { tieBreak: tieBreaks }
  };

  Championship
    .update(query, newValues)
    .exec((err, result) => {
      if(err) callback (false);
      else {
        if (result.nModified > 0) {
          callback(true);
        } else {
          callback(false);
        }
      }
    });
}

And the result is :

"tieBreak": [[{
  "_id": ObjectId("5ac61f8002e836a14c4ab2b1"),
  "name": "wins"
},
{
  "_id": ObjectId("5ac61f8002e836a14c4ab2b0"),
  "name": "balance"
}]]

This means that this function added a List of TieBreaks inside one tieBreak document, but my intention is to add a list of TieBreaks and each value of that list fill just one document, the return should me like this:

"tieBreak": [{
  "_id": ObjectId("5ac61f8002e836a14c4ab2b1"),
  "name": "wins"
},
{
  "_id": ObjectId("5ac61f8002e836a14c4ab2b0"),
  "name": "balance"
}]

How can I do it?

Thank you

like image 644
Vinicius Martin Avatar asked May 10 '26 17:05

Vinicius Martin


1 Answers

Try this:

function createTable (idChampionship, tieBreaks, callback) {
  const query = { _id : idChampionship };

  // assuming tieBreaks is an array. without $each, mongoose just pushes the array as is.
  const newValues = {
    $addToSet: { tieBreak: {$each: tieBreaks } }
  };

  Championship
    .updateOne(query, newValues)
    .exec((err, result) => {
      if(err) { 
          callback(false);
      } else {
          callback(result.nModified > 0);
      }
    });
}
like image 144
Igal Klebanov Avatar answered May 14 '26 14:05

Igal Klebanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!