【问题标题】:How to send array into API call to set a list of objects - angular如何将数组发送到 API 调用以设置对象列表 - 角度
【发布时间】:2015-10-30 00:47:37
【问题描述】:

我有这个:

在我的 API 中:

router.post('/setsuggestions', auth, function(req, res, next){
  if(!req.body.username || !req.body.challengessuggestions){
    return res.status(400).json({message: challengessuggestions});
  }

  var query = { username: req.body.username };
  User.findOneAndUpdate(query, { challengessuggestions: req.body.challengessuggestions }, callback = function(){
    //console.log("Ja");
  });
  res.json(200);

});

challengesuggestions 是挑战列表。

我在我的 Angular 应用程序中使用此代码:

auth.setsuggestions = function(user, suggestions){
            console.log(suggestions);
            return{
                getValue: function(){
                    $http({
                        method: 'POST',
                        url:'http://groep6api.herokuapp.com/setsuggestions',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        transformRequest: function(obj) {
                            var str = [];
                            for(var p in obj)
                                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                            return str.join("&");
                        },
                        data : {username: user, challengessuggestions: suggestions}
                    }).then(function (result) {
                        //$route.reload();
                        //$window.location.reload(true)
                    });
                }
            }
        }

Console.log(suggestions) 给我:

这不会在我的数据库中设置任何内容。

当我使用邮递员时,我得到一个 API 调用成功的 200 答案,但数据库中没有设置任何内容。这是邮递员的配置:

如何正确设置挑战(对象)列表?

【问题讨论】:

  • 您是否从 angularjs $http 请求中获得成功或错误响应?然后尝试添加匿名错误函数。 .then(function (success) {}, function (error) { console.log(error) }
  • 首先,您不想在“findOneAndUpdate”调用之后发送响应吗?移动'res.json(200);'进入'findOneAndUpdate'函数回调体。
  • 好的,设置1个挑战成功了,但是如何设置一系列挑战呢?我在邮递员中使用了这个:563141ab8c5ba50300f2b4f5

标签: angularjs node.js express mongoose


【解决方案1】:

如果您使用 MongoDB,您应该考虑使用像 Mongoose 这样的数据模型来处理与数据库的交互。

【讨论】:

  • 这可能是你应该开始的地方
【解决方案2】:

https://docs.mongodb.org/manual/reference/operator/update/push/#up._S_push

你可以修改

    { challengessuggestions: req.body.challengessuggestions } to
    { challengessuggestions: {$push: req.body.challengessuggestions}

$push 运算符将指定的值附加到数组中

如果您从请求正文接收到一个数组,那么将键设置为该值就足够了。

也是您应用它来包含挑战建议的模型吗?

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 2017-09-07
    • 2019-07-19
    • 1970-01-01
    • 2020-10-28
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多