Thanks for the example Siegfried.
I would get the same issue as well, mainly that after I updated an
embedded document and saved it, it would produce a duplicate embedded
document but with the updated values. In my case, something like this:
> db.fightmonsters.find()
{ "_id" : ObjectId("4d67d041e6a3b9d00c00000a"), "player" : [
{
"_id" : ObjectId("4d67d041e6a3b9d00c00000b"),
"name" : "Warrior",
"action" : "attack",
"hp" : 100,
"target" : ObjectId("4d67d03ae6a3b9d00c000001")
},
{
"_id" : ObjectId("4d67d041e6a3b9d00c00000c"),
"name" : "Monster 1",
"action" : "attack",
"hp" : 50,
"target" : ObjectId("4d5c35b0cdebc4780600000c")
},
{
"_id" : ObjectId("4d67d041e6a3b9d00c00000b"),
"name" : "Warrior",
"action" : "attack",
"hp" : 90,
"target" : ObjectId("4d67d03ae6a3b9d00c000001")
},
{
"_id" : ObjectId("4d67d041e6a3b9d00c00000c"),
"name" : "Monster 1",
"action" : "attack",
"hp" : 50,
"target" : ObjectId("4d5c35b0cdebc4780600000c")
}
], "status" : "Open", "user_id" :
ObjectId("4d571cfffa51b72407000005") }
However, following Siegfried's example, if at first you pull the saved
record from the database and work with that variable, instead of the
initial variable, then you do not get duplicate entries:
fightSession was the initial variable using "new", and session is the
variable with the pulled data:
fightSession = new FightMonster({
user_id:
req.curUser.id,
status: 'Open',
});
fightSession.player.push({
name:
req.curChar.name,
action: req.params.action,
hp: req.curChar.stats.hp,
target: curMonster.id,
});
fightSession.player.push({
name: curMonster.name,
action: 'attack',
hp: curMonster.stats.hp,
target:
req.curChar.id,
});
fightSession.save(function(err){
if(!err){
FightMonster.findOne({ status: 'Open' }, function (err,
session){
if(session){
session.player[0].hp += 20;
session.save(function(err){
console.log(session.toObject());
});
}
});
...