0

Hey I am trying to allow users to update their emails in an array. I want to update a specific email of theirs if they click on edit. I have the old value and the new value, I know I can do a pull and push but wanted to see if I can do it in a more efficient way with matching the value with the $elemMatch then $set it with the new value? I tried the positional operator but it does not work for just values in an array without a key relationship meaning fieldx: value x... here is my attempt, not sure how to go about it? Other directions are welcomed.

User.findByIdAndUpdate(req.signedCookies.userid,{
            emailList: { $elemMatch: {oldEmail, {$set: {req.body.updateEmail}}}}
        }, function(err, userX) {});
Lion789
  • 4,402
  • 12
  • 58
  • 96
  • Have you tried something similar to [this](http://stackoverflow.com/questions/6758339/updating-embedded-document-property-in-mongodb) ? – Rafael Barros Aug 16 '13 at 22:39
  • Yeah it does not work for me my problem is different because my array is just values, should I be adding a field for each value to keep it in a key pair like so email: value, email: value etc... – Lion789 Aug 17 '13 at 04:22

1 Answers1

0

The MongoDB syntax would be

> db.test.insert({userId: '1234', emailList: ['abc', 'def']})
> db.test.find()
{ "_id" : ObjectId("520eaade49177daf439a2ffa"), userId: '1234', "emailList" : [ "abc", "def" ] }
> db.test.update({userId: '1234', emailList: 'abc'}, {$set: {'emailList.$': 'ghi'}})
> db.test.find()
{ "_id" : ObjectId("520eaade49177daf439a2ffa"), userId: '1234', "emailList" : [ "ghi", "def" ] }
>

The Mongoose code would then be

User.findOneAndUpdate({userId: '1234', emailList: 'abc'}, {$set: {'emailList.$': 'ghi'}})

This will allow you to make the change in one query as opposed to a $pull and $push

Since you're searching an array of values and not an array of documents, you don't need $elemMatch. You can just query the array directly and MongoDB knows to look inside it and match a value.

Mason
  • 8,767
  • 10
  • 33
  • 34
  • Yeah, how do I go about doing that because I am not sure how to work what you got up there in findByIdAndUpdate({_id: userCookie, emailList: oldEmail}, {$set: {'emailList.$': newEmail} – Lion789 Aug 17 '13 at 00:38
  • Yeah, I tried that it is not working... keeps giving me this error: { message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"' name: 'CastError', type: 'ObjectId', value: { _id: 'userCookie', emailList: 'oldEmail' }, path: '_id' } – Lion789 Aug 17 '13 at 00:42