Search code examples
node.jsgetmongooseput

How to update subdoc data in Mongoose


I am trying to update user.task.fixitItem, where the Task schema is embedded within the User schema.

Using this get,

app.get('/api/tasks/:id/edit', isAuthenticated, function (req, res) {
  console.log('*** testing route GET /api/tasks/:id/edit', req.params);

  User.findOne({'task._id': req.params.id})
    .select('task.$')
    .exec(function(err, user) {
      if(!user) {
        res.statusCode = 404;
        return res.send({ error: 'Not found' });
      }
      if(!err) {
        return res.render('tasks/edit', {task: user.task[0] });
      } else {
        res.statusCode = 500;
        console.log('Internal error(%d): %s', res.statusCode, err.message);
        return res.send({ error: 'Server error' });
      }
    }
  );

});

How do you write the put to update the data?


Solution

  • You need to use the update method with $set

    User.update(
      { 'task._id': req.params.id }, 
      { $set: { 'task.$.fixitItem': 'new value' }},
      function(err, user) {
    
      }
     );