5

Trying to update an object in an array.

My code:

module.exports = (req, res) => {

  var givenProject = req.body;
  var query = mongoose.model('cv').findOne({alias: req.params.alias});

  query.exec(function(err, cv){
    if(err){
      res.status(400).send({message: 'Could not find cv with alias: ' + req.params.alias, err: err})
     }
    var doc = cv.projects.id(req.params.id);
    doc.langTitles = givenProject.langTitles;
    doc.langDescriptions = givenProject.langDescriptions;
    doc.save(function(err){
      if(err){
        res.status(400).send({message: 'Could not update project', err: err});
        return;
      }
      res.status(200).send();
    });
  });
};

No error is given. var doc is found and the posted data have the same data structure as doc and it differs from the original.

The doc is not updated. What am I missing here?

2
  • What is doc after the line var doc = cv.projects.id(req.params.id);? What is cv.projects? Is cv.projects.id a function? Commented Sep 29, 2016 at 14:01
  • Its a built in function in mongoose to find subdocuments. mongoosejs.com/docs/subdocs.html Commented Sep 29, 2016 at 14:02

1 Answer 1

4

According to the Mongoose docs:

Sub-documents enjoy all the same features as normal documents. The only difference is that they are not saved individually, they are saved whenever their top-level parent document is saved.

Therefore try replacing

doc.save(function(err) ...

with

cv.save(function(err) ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.