0

I don't understand why mongoDB does this so maybe someone can explain...below are my schemas and code,

-using mongoose-

var postSchema = new mongoose.Schema({
  raidName: String,
  raidDate: String,
  raidTime: String,
  raidFaction: String,
  whosGoing: { type: Array, "default": []}
});


var realmSchema = new mongoose.Schema({
  realmName: String,
  posts: [postSchema]
});

below is how my database looks

{
    "_id": {
        "$oid": "581447f5fb4fab06dcbf10a6"
    },
    "realmName": "Cho'gall",
    "posts": [
        {
            "raidName": "wailing cavs",
            "raidDate": "Sat Oct 29 2016",
            "raidFaction": "Horde",
            "raidTime": "1:01 AM",
            "_id": {
                "$oid": "58144806fb4fab06dcbf10a7"
            },
            "whosGoing": [
                {
                    "role": "DPS",
                    "gender": "Male",
                    "race": "Orc",
                    "classImg": "../images/class_photos/monk.png",
                    "class": "Monk",
                    "level": 90,
                    "name": "Monnky"
                }
            ]
        }
    ],
    "__v": 1
}

I am able to create new posts no problem, however I don't know how to add more objects to the 'whosGoing' array.... below is what im doing..

  var Realms = mongoose.model('realms');

  Realms.findOne({realmName: realm}, function (err, realm) {
    realm.posts.id(postId).whosGoing.push(thisChar); //pushing it here no problem
    console.log(realm.posts.id(postId).whosGoing); //when i log it here both objects are in the array just fine
    console.log(realm); //but when i log the realm here, the item i just pushed is not in there, so of course if I realm.save() it wouldnt take effect...
    realm.save();
  })

can someone explain why this is happening please..

Yandri
  • 41
  • 4

2 Answers2

1

There is a similar question here

But basically you can use &elementMatch to find the desire post in the array, and use the positional $ operator which identify the post matched in the query. Example:

var query = {
  "realmName": realm,
  "posts": { 
    $elemMatch: { 
      "_id": postId
    } 
  }
}

var setField = {
  $addToSet: {
    "posts.$.whosGoing": thisChar
  }
}

Realms.update(query, setField, function(err, results){
  if (err){console.log(err)}
  else {
   console.log(results);
  }
}
Community
  • 1
  • 1
lucas.coelho
  • 894
  • 1
  • 9
  • 16
0

Use $push operator:

Realms.update({ realmName: realm }, { $push: { whosGoing: thisChar } }, ...)

Also there is $pull operator for removing value from array.

styopdev
  • 2,604
  • 4
  • 34
  • 55