juju
juju

Reputation: 326

How to merge 2 arrays with mongoose?

Array 1 = [X, , , , ,X]

Array 2 = [ , , ,O, , ]

I want to merge array 1 with array 2 to get this result: [X, , , O, ,X] instead of replacing Array 1 with array 2..

My code:

tictactoe.put('/updateBoard/:gameId', function (req, res) {
    Game.findOneAndUpdate({"gameId": req.params.gameId}, {
        "$set": {
           gameProgress: req.body.board
        }
    }, (err, data) => {
        if (err) {
            return res.status(500).send(err);
        }
        return res.status(200).json(data);
    });
});

Any ideas?

Upvotes: 0

Views: 411

Answers (1)

Nick
Nick

Reputation: 352

I'm assuming you want to merge 'gameProgress' which is an array, with req.body.board which is also an array.

{ $addToSet: { gameProgress: { $each: req.body.board } } }

This will add each array element of req.body.board into gameProgress.

Upvotes: 1

Related Questions