I cannot get to update my documents using mongoose with the positional $ operator. This is a follow-up question strongly related to this question : Mongoose update 'cannot use the part (..) to traverse the element
I looked up here : http://docs.mongodb.org/manual/reference/operator/update/positional/ and did exactly as they do in the example:
User.update({'local.email' : user, 'devices.id' : deviceID},
{$set : {'devices.$.agenda' : agenda}}, function(err, response)
{
if(err)
{
console.log("Update agenda error", err);
}
else {
console.log("Update agenda OK");
console.log("Response", response);
}
});
But response returns
Response { ok: 1,
nModified: 0,
n: 0,
lastOp: { _bsontype: 'Timestamp', low_: 2, high_: 1434882344 },
electionId: 555637ca17aac10c2bbc5d84 }
So nothing gets modified. I tried to query only to see if i manage to find the requested ID and i cannot find it even though i use the exact same variables i used for insertion.
UPDATE The user schema:
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
},
devices : [{
id : String,
name : String,
agenda : String
}]
});
UPDATE #2
The code that makes the updates is the following :
function updateDeviceList(user, deviceID, deviceName)
{
User.update({ 'local.email' : user},
{ $push: {'devices' : {'id': deviceID, 'name':deviceName, 'agenda' : ""}}},
function(err, response)
{
if(err)
{
console.log("Update device error", err);
}
else {
console.log("Update device OK");
}
});
}
function updateAgenda(user, deviceID, agenda)
{
User.findOneAndUpdate({'local.email' : user, 'devices.id' : deviceID},
{$set: {"devices.$.agenda" : agenda}},
{ select: {
'devices': {
$elemMatch:
{ 'id' : deviceID }
}
}
},
function(err, response)
{
if(err)
{
console.log("Update agenda error", err);
}
else {
console.log("Updated agenda OK");
console.log("respnse", response);
}
});
console.log("user", user);
console.log("deviceID", deviceID);
console.log("agenda", typeof agenda);
}
The user
and the deviceID
are both strings and are the same values used in both functions. Agenda console.log returns string
.