Reputation: 2266
I'm using NodeJS and Mongoose to store data to a MongoDB database. It is mostly working fine, as I'd expect.
I have an array, as part of a Schema, saved to a database document in Mongoose. It looks like this, in the Schema:
var GameSchema = new mongoose.Schema({
...
PlayerOrder: [Number],
...
}
When I call a findOne(...)
to get this document from the DB, it works as expected, and I get a result, let's say ... [1,2,3,4] ...
.
Then, within the callback that's fired on successful findOne(...)
execution, I modify some values, including PlayerOrder itself and other values. I verify before saving to the DB, via console, that the changes were made to the local GameModel object. One of these changes is to reverse the PlayerOrder array using `game.PlayerOrder.reverse();'. Then I use the GameModel.save(...) function.
Here are some snippets of the code:
if (game.Turn >= game.PlayerCount) {
console.log('Commuting to Phase 3.');
game.Phase = 3;
game.Turn = 0;
// in phase 3, the player order is reversed; do that here
console.log('player order before reverse: ' + game.PlayerOrder);
game.PlayerOrder.reverse();
// NOTE: this verifies that the array is correctly reversed in the model
console.log('player order after reverse: ' + game.PlayerOrder);
}
game.save( function (err, game) {
if (err) console.error(err);
console.log('+ + + Execution successful; DB updated.');
});
Then, when I pull the same document from the DB again, all the changes I made are there. In other words, after pulling the document I can see that all the changes I made to the document elements, such as player cash, game board state, etc, were all correctly made, and saved in the save(...)
function. EXCEPT for the reversed array, which never gets modified for some reason.
Why?
Upvotes: 2
Views: 738
Reputation: 14562
This happens because Mongoose can't track the changes made in the array when you used reverse()
.
In order to notify the changes, use markModified()
, like this:
if (game.Turn >= game.PlayerCount) {
console.log('Commuting to Phase 3.');
game.Phase = 3;
game.Turn = 0;
// in phase 3, the player order is reversed; do that here
console.log('player order before reverse: ' + game.PlayerOrder);
game.PlayerOrder.reverse();
game.markModified('PlayerOrder'); // <== this line notifies Mongoose of the change
// NOTE: this verifies that the array is correctly reversed in the model
console.log('player order after reverse: ' + game.PlayerOrder);
}
More info on this, Mongoose FAQ has some answers.
Upvotes: 1