title: Mongoose: How do I replace an array of subdocuments?
body: <p>I have set up a user schema with mongoose which contains a subdocument "contacts". The subdocument "contacts" is a collection of contacts objects which contain the actual contact (reference to another user object) and some data which is related to the "friendship".</p>
  
  <p>In my front-end application I can now manage the contacts by adding or removing users to my contact list. The front-end saves these changes as HTTP PUT requests to the server.</p>
  
  <p>The PUT request contains the whole user object which more or less replaces the user object on the database. Unfortunately it is not possible to replace subdocument collection. You only can  push new ones or remove them. </p>
  
  <p>Here are the schemas:</p>
  
  <pre><code>var UserSchema = new Mongoose.Schema({
  
      username: { 
          type: String, 
          index: { unique: true, sparse: true }, 
          required: true, lowercase: true, trim: true
      },
  
      email: {
          type: String,
          index: { unique: true, sparse: true }, 
          required: true, lowercase: true, trim: true
      },
  
      contacts: [ContactSchema]
  
  });
  
  var ContactSchema = new Mongoose.Schema({
  
      user: {
          ref: "User",
          type: Mongoose.Schema.ObjectId
      },
  
      isContact: {
          type: Boolean,
          default: true
      }
  
  });
  </code></pre>
  
  <p>Currently I try to replace the contacts by removing all and adding the one in the request:</p>
  
  <pre><code>app.put('/me', loadUser, function(req, res, next) {
      var user = req.user;
  
      req.user.contacts.forEach(function(contact) {
          req.body.contacts.forEach(function(contact) {
              contact.remove();
          });
      });
  
      req.body.contacts.forEach(function(contact) {
          req.user.contacts.push(contact);
      });
  
      user.save(function(err, user) {
          if (err) return next(err);
          res.send(200);
      });
  });
  </code></pre>
  
  <p>Has somebody actually an better idea how I can update this subdocument collection to the state in the request?</p>