3

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

3 Answers 3

4

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);
      }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Currently, you can do it as follows:

const filter = { _id : idChampionship }
const update = { $push: { tieBreak: { $each: tieBreaks }}}
Championship.updateOne(filter, update)

Comments

-2

I think that the best way is do it step by step. For example:

1- Get championship 2- forEach tieBreak, push in championship 3- Save.

=)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.