3

Possible Duplicate:
Can mongo upsert data?

I have schemas defined as follows:

var Permission = new Schema({
  _id: String,  // email address
  role: String  // "admin" or "member"
});

var Org = new Schema({
  name: {type: String, index: {unique: true, dropDups: true}, trim: true},
  permissions: [Permission]
});

I am trying to either match and update a subdocument row (in my case, 'permissions', or insert a new permissins row if no match (e.g. upsert).

Here is what I have written:

exports.updatePermissions = function(req, res) {
  return Org
    .update(
      {name:"my_org", "permissions.$._id": req.body.email},
      {$set: {"permissions.$.role": req.body.role}})
    .exec(function(err) {
      // stuff
    });
};

MongoDB seems to accept this (e.g. no errors), but there is no change in the DB. I tried the following in the mongo shell as well:

db.orgs.update({"name":"my_org", "permissions.$._id":"newuser@email.com"}, {$set: {"permissions.$.role": "member"}});

Again, Mongo accepted the query, but no change. Here is the document that I am trying to modify:

{
    "name" : "my_org",
    "permissions" : [
        {
            "_id" : "newuser@email.com",
            "role" : "admin"
        }
    ]
}

Any suggestions? Many thanks

Community
  • 1
  • 1
Scott Switzer
  • 1,064
  • 1
  • 15
  • 25

1 Answers1

0

This works for me with $elemMatch, also check out the rules for the $ operator:

db.orgs.update({"name":"my_org", "permissions": {$elemMatch: {_id:"newuser@email.com"}}},
     {$set: {"permissions.$.role": "member"}});
mjhm
  • 16,497
  • 10
  • 44
  • 55
  • 1
    Thanks. This works for me to update an existing entry, but it does not insert a non-existant entry (I added upsert=true as well). Do you have advice on how the upsert would work here? – Scott Switzer Jan 10 '13 at 01:39
  • I think your out of luck on the upsert. The "$" operator doc specifically warns against using it for "upsert" operations. – mjhm Jan 10 '13 at 03:43