Skip to content

Instantly share code, notes, and snippets.

@bertrandmartel
Last active February 15, 2017 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bertrandmartel/7b21021b9097791b5cf540c13cb84bd5 to your computer and use it in GitHub Desktop.
Save bertrandmartel/7b21021b9097791b5cf540c13cb84bd5 to your computer and use it in GitHub Desktop.
[SO] update with positional parameter & parameterized field name
//http://stackoverflow.com/questions/42234713/updating-info-with-mongoose-array-inside-object-inside-object-dynamically/42238863#42238863
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/accounts');
const Schema = mongoose.Schema;
const championSchema = new Schema({
champ_1: String,
champ_2: String,
champ_3: String
}, { _id: false });
const playerSchema = new Schema({
history_moves: [String],
champions: [championSchema]
}, { _id: false });
const matchSchema = new Schema({
room: String,
player_1_details: playerSchema,
player_2_details: playerSchema
});
//Update Champion
matchSchema.statics.update_champ = function(room, turn, champ_num, champ_select, callback) {
var modifier = { $set: {} };
modifier.$set['player_' + turn + '_details.champions.$.champ_' + champ_num] = champ_select;
var match = {};
match['room'] = room;
match['player_' + turn + '_details.champions.champ_' + champ_num] = { $exists: true };
this.update(match, modifier)
.exec(function(error) {
if (error) {
return callback(error);
} else {
return callback(null);
}
});
};
var Match = mongoose.model('Matches', matchSchema);
Match.update_champ("room_0.0940045412694186", 1, 3, "new_value", function(err, res) {
if (!err) {
console.log(err);
return;
}
console.log(res);
});
/*
//insert item
var match = new Match();
match.room = "room_0.0940045412694186";
match["player_1_details"] = new Player({
"history_moves": [],
"champions": [{
"champ_1": "na"
}, {
"champ_2": "na"
}, {
"champ_3": "na"
}]
});
match["player_2_details"] = new Player({
"history_moves": [],
"champions": [{
"champ_1": "na"
}, {
"champ_2": "na"
}, {
"champ_3": "na"
}]
});
match.save(function(err, req) {
console.log(err);
console.log(req);
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment