【问题标题】:How to update subdoc data in Mongoose如何在 Mongoose 中更新 subdoc 数据
【发布时间】:2015-01-21 18:41:02
【问题描述】:

我正在尝试更新 user.task.fixitItem,其中任务架构嵌入在用户架构中。

使用这个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' });
      }
    }
  );

});

如何写put来更新数据?

【问题讨论】:

    标签: node.js get mongoose put


    【解决方案1】:

    你需要使用 $set 的更新方法

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

    【讨论】:

    • 啊哈,我相信我的获取只是传递子文档而不传递父 user._id。我还需要弄清楚如何传递它,然后我可以按照你的建议更新用户。
    • 我是这样设置的
    • app.put('/api/tasks/:id', isAuthenticated, function (req, res) { User.update({ 'task._id': req.params.id }, { $set: { 'task.$.fixitItem': 'new value' }} .exec(function(err, user) { console.log("Updated Existing Task with ID: " + req.params.id); return res.render('/dashboard'); }) ); }); 我现在收到此错误"message": "Object # has no method 'exec'", "error": {}
    • 你实际上需要删除 exec(),我已经修改了我的答案
    猜你喜欢
    • 2016-08-05
    • 2014-05-21
    • 2016-09-27
    • 2017-05-20
    • 2018-12-29
    • 2018-11-28
    • 2018-04-29
    • 2018-09-02
    • 1970-01-01
    相关资源
    最近更新 更多