0

I'm quite new with Mongoose, I'm trying to get familiar with it,but the poor documentation doesn't help (no search, no list of functions,..).

I have a document that represents a Company, and subdocuments that represents the users:

{
    "_id": "57ffa47f5b70f90831212348",
    "name": "mycompany",
    "address": "...",
    "phone": "...",
    "users": [
        {
            "_id": "57ffa47f5b70f90831212347",
            "username": "alpha",
            "name": "myname",
            "surname": "mysurname",
            "password": "..."
        }
    ]
}

I want to find a particular subdocument and update just some fields (name,surname, password,...) that are passed from frontend.

I receive req.body that contains the fields edited (i.e. req.body.name) and req.user that contains the user logged:

"company_shortname": "CMPNY",
    "company_id": "57ffa47f5b70f90831212348",
    "user": {
        "id_access_level": 0,
        "surname": "ltd",
        "name": "mycompany",
        "username": "mycompanyusername",
        "_id": "57ffa47f5b70f90831212347",
        "password": "..."
    }
}

what I want to obtain is find the subdoc edited (the company that contains this subdoc will be always the same of the user logged in), update data passed, and save.

Using this answer, I tried:

Company.find({'_id': req.user.company_id}).select('name').exec(
        function(err, company) {

          if (err) res.status(500).send(err);

          var partialUpdate = req.body;

          var set = {};
          for (var field in partialUpdate) {
          set['users.$.' + field] = partialUpdate[field];
          }

          company.update({_id: req.user._id, "users._id": req.body._id},
          {$set: set},
          function(err, numAffected) {
            console.log('Number of users edited: ' +JSON.stringify(numAffected,null,4));
          });
      });

but I cannot get it to work.. any ideas?

Community
  • 1
  • 1
Don Diego
  • 1,309
  • 3
  • 23
  • 46

1 Answers1

1

I solved using this query:

//saving in 'set' the fields to be edited
var partialUpdate = req.body;
    var set = {};
    for (var field in partialUpdate) {
    set['users.$.' + field] = partialUpdate[field];
    }

    //find the company,then the subdoc, then set the fields with 'set'
    Company.findOneAndUpdate({
      '_id': req.user.company_id, "users._id" : req.body._id},
      {$set: set},
      function(err, company) {
        //the company status after the update
        console.log('company updated: ' +JSON.stringify(company,null,4));
      });
Don Diego
  • 1,309
  • 3
  • 23
  • 46