【问题标题】:Local Node API not POSTing to Mongoose DB本地节点 API 未发布到 Mongoose DB
【发布时间】:2016-03-30 07:44:44
【问题描述】:

谁能告诉我为什么我的 POST 方法没有通过 Mongoose 保存到我的 MongoDB 中?

我的 Angular 控制器

$scope.saveUpdate = function(id){
    $http.post('/api/entry/' + id)
        .success(function(data){
            $scope.entry = data;
        })
        .error(function(data){
            console.log('There was a problem saving your entry: ' + data);
        });
    // update page with remaining entries
    $http.get('/api/entries').then(function(response){
        $scope.entries = response.data;
    });
}

我的 API

app.post('/api/entry/:entry_id', function(req, res){
    if (req.params) {
      Entries.findByIdAndUpdate({
        _id : req.params,
        // the properties we're updating and the new values
        username: req.body.username,
        date: req.body.date,
        income: req.body.income
      }, function(err, entry){
        if (err) {
          res.send(err) }
          else {
            res.send('Success!');
          }
      })
    }
});

视图中的提交按钮

<button type="submit" class="btn" ng-click="saveUpdate(entry._id)">Update</button>

当点击按钮时,更新的条目会到达 DOM,但当它到达 Angular 核心代码时,它会恢复到原始状态而不更新数据库。也不会抛出任何错误。

【问题讨论】:

    标签: angularjs node.js mongodb express mean-stack


    【解决方案1】:

    上面的代码有几处错误:

    1. 整个req.paramsobject 被传递到_id 字段而不是req.params.entry_id
    2. 将参数传递给findByIdAndUpdate() 的方式不正确
    3. 请求正文永远不会在您的 $http.post() 中发送,但您希望 req.body 包含您的路由中的数据

    req.params 指向请求中的整个 params 对象。您只想从参数中获取 ID,然后将其传递给您的 mongoose 模型。

    假设您传递的是entry_id,那么您将传递您的第一个条件if(req.params),因为参数确实存在。但是,当您将 req.params 传递给 Entries 模型的 _id 字段时,您实际上是在传递整个对象 { entry_id: '123' } 而不仅仅是 123

    此外,您将值传递给findByIdAndUpdate 方法的方式不正确。 findByIdAndUpdate(id, [update], [options], [callback]) 需要 4 个参数,id 是唯一必填字段。您传入整个对象以根据 id 查找并更新单个参数中的值。您需要从要更新的字段中拆分出entry_id

    app.post('/api/entry/:entry_id', function(req, res) {
    
      // Param Existence Checking
      if (!req.params.entry_id)
        return res.status(400).send('an entry_id must be provided');
      if (!req.body.username)
        return res.status(400).send('a username must be provided');
      if (!req.body.date)
        return res.status(400).send('a date must be provided');
      if (!req.body.income)
        return res.status(400).send('an income must be provided');
    
      var updateData = {
        username: req.body.username,
        date: req.body.date,
        income: req.body.income
      };
    
      Entries.findByIdAndUpdate(req.params.entry_id, updateData, function(err, entry){
        if (err)
          return res.status(500).send(err)
    
        return res.status(200).send('Success!');
      })
    
    });
    

    同样基于您问题中的示例代码,我看不到您在执行$http.put() 时将值传递给req.body 的位置。可以肯定的一件事是,如果req.body 不包含usernamedateincome,您将获得undefined 分配给这些字段。

    要通过$http.post() 提供请求正文,请将其传递给第二个参数data

    $http.post('/api/entry/' + id, {
      username: 'username',
      date: new Date(),
      income: 10000.00
    })
      .then(function(res, status){ 
        console.log(res.data);
      })
      .catch(function(err) {
        console.log(err);
      });
    

    另外,不要在你的承诺链中使用.success()that approach is deprecated。在处理您的回复时,您应该使用 A+ 标准 .then().catch()

    【讨论】:

    • 我明白你在说什么。将entry_id 替换为我的请求后,不幸的是仍然没有更新数据库。当它在 angular.js 核心文件中遇到 completeRequest 回调时,它会恢复到原始条目。不知道为什么会这样。
    • @PanicBus 看到我的回答,我在回答中更新了对Entries.findByIdAndUpdate() 的调用。第一个参数应该是要匹配的_id 值,即req.params.entry_id。第二个参数是要更新的字段及其值的对象。您正在将您的字段传递给更新,并将您的 ID 传递给一个对象和一个不正确的参数。 Model.findByIdAndUpdate Docs
    • 我知道发生了什么。你是对的,body 作为一个空对象 body: {} 进来。您会立即知道为什么会这样,以及如何解析来自 req 的数据吗?我已经包含并使用了 body-parser 中间件。
    • 这是一个很好的更新,但现在我从我的控制器中得到了这个:POST localhost:3000/api/entry/56faf8739777cb3181141b1d 400(错误请求)我没有将它硬编码到控制器中,而是从表单中获取我的数据@ 987654364@
    • 好的,完成了。感谢您的帮助。在提交按钮中添加了一个参数来捕获更新数据entry 并将其传递给 .post 对象。 $scope.saveUpdate = function(id, entry){..entry.username
    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2017-09-14
    • 2021-08-05
    • 2021-03-13
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多