Reputation: 189
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
Upvotes: 3
Views: 1743
Reputation: 313
Currently, you can do it as follows:
const filter = { _id : idChampionship }
const update = { $push: { tieBreak: { $each: tieBreaks }}}
Championship.updateOne(filter, update)
Upvotes: 0
Reputation: 368
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);
}
});
}
Upvotes: 4
Reputation: 124
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.
=)
Upvotes: -2