title: MongoDB. How to update json property inside an array
body: <p>I'm using the Mean stack. I'm uncomfortably new to this and have got myself in a pickle. I've seen examples of updating records using set or push but because I'm trying to update one json object within a json object within an array of json objects I'm having trouble.</p>
  
  <p>Consider the following Schema</p>
  
  <pre><code>token: {
      type: String,
      required: "FB access token required."
  },
  fbId: {
      type: String,
      required: "FB id required.",
      unique: true
  },
  accounts: {
      type: Array,
      default: []
  }
  </code></pre>
  
  <p>My accounts array consists of json objects, each of which look like this:</p>
  
  <pre><code>{
     "name": "some name",
     "credentials": {
         "username": "some username",
         "password": "some password"
  }
  </code></pre>
  
  <p>I'm trying to update accounts each time the user adds a new one. So in this case I can use $push just fine. But I don't want duplicate names, and $push fails here.  So I tried using $set, but $set isn't inserting objects with new names into accounts. So I tried using upsert:true with $set, but now I'm getting duplicate errors. </p>
  
  <p>Here is an example where I try to index name in accounts. I'm assuming I'm screwing up my query some how.</p>
  
  <pre><code>var name = "some name";
  var fbId = "some fb Id";
  var token = "some token";
  var username = "some other username";
  var password = "some other password";
  
  var query = {
      fbId: fbId,
      token: token,
      "accounts.name":name
  };
  var update = {
      $set: {
           accounts: [{
              name: name,
              credentials: {
                  username: username,
                  password: password
              }
          }]
      }
  
  };
  var options = {
      upsert: true
  };
  User.update(query, update, options,
      function (err, numberAffected, rawResponse) {
          //handle it
      });
  );
  </code></pre>
  
  <p>To sum up my question, is it reasonable to think I can update this with one call and if so how? Or should I find the object, replace its values and then reinsert it to the database?</p>