0

Heres what my mongoose schema looks like-

const GameLogSchema = new Schema({      
    _score: Number,
    _playerData: {
        x: Number,
        y: Number,
    },
    _zoneData: [{ _x: Number, _height: Number }],
    _pipeData: [{ _x: Number, _randomeHeightTop: Number }],
    _gap: Number,
});

const PlayerSchema = new Schema({
    /* other fields */

    _gameLogs: {
       type: [[GameLogSchema]],  
    },
}); 

This is what the data its supposed to deal with looks like - gameLogs

Spreading one of those objects - gameLogs-spreaded

How to push an array of objects having arrays, into an array ? preferably in nodejs mongoose.


EDIT -

I tried to do something similar to whats given in Mongodb $push in nested array

I tried this with my schema -

const PlayerSchema = new Schema({
    /* other fields */

    _gameLogs: [
      {
          _logs: [{ _log: { _score: Number } }],
      },
    ],
}); 

And heres my update function -

Player.findOneAndUpdate(
            { \* filter *\ },
            {
                $push: {
                    /* pushing something other, that works */

                    _gameLogs: {
                        '_gameLogs.$._logs': {
                            '_logs.$._log': { '_log.$._score': req.body.gameLogs.score },
                        },
                    },
                },
                $inc: { _totalGamesPlayed: 1, '_gameStreak._gamesPlayed': 1 },
            },
            { safe: true, upsert: true, new: true, minimize: false },
            (err, result) => {
                console.log(result);
            }
        );

It outputs a list of { _logs: [], _id: 5f4f5979fba2d03c40d4aed7 }, among other things.

user9586876
  • 81
  • 1
  • 2
  • 8
  • Does this answer your question? [Mongodb $push in nested array](https://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array) – turivishal Sep 02 '20 at 08:29
  • @turivishal naah it doesn't. Mine has an extra layer compared to the one you posted and and the sub array is unnamed. I tried it tho. I'm posting what I did in the edit. – user9586876 Sep 02 '20 at 10:10
  • you are doing wrong. look at the suggested question again, you need to do this way `$push: { '_gameLogs.$._logs': { '_log._score': req.body.gameLogs.score } }` and also it requires to put condition in query part for that array. – turivishal Sep 02 '20 at 13:04
  • @turivishal it doesn't work. and your code might work if I was pushing an array inside an array. But what I am doing is pushing an array inside an array which contains objects which also has arrays inside. Its something like - `[ { a:[ ], b: [ ] }, { a:[ ], b: [ ] }, ]`. I am trying to push this inside a Array field . – user9586876 Sep 02 '20 at 14:02

0 Answers0