javascript - 使用 JQuery、ExpressJS 和 AJAX 更新 MongoDB

标签 javascript ajax mongodb express post

我有一个使用 type: 'DELETE' 这样的删除函数,我现在正在尝试创建一个更新函数,尽管我不知道我是否正确地执行了此操作,到目前为止的代码如下:

ejs:

<a href="#" class="editEvent" data-id="<%= event._id %>">Edit</a></p>

js:

$(document).ready(function(){
    $('.editEvent').on('click', editEvent);
});

function editEvent(){
    var change = prompt('Change to:', '');

        $.ajax({
            type:'UPDATE',
            url: '/events/update/'+$(this).data('id'),
            data: change
        }).done(function(response){
            window.location.replace('/');
            });
}

应用程序.js:

app.post('/events/update/:id', function(req,res){
    db.events.update({_id: ObjectId(req.params.id)}, {$set: {event_name: data}},function(err, result){
        if(err){
            console.log(err);
        }
        res.redirect('/');
    });
});

所以我想使用 $set 在 MongoDB 中进行更新,并将 event_name 设置为用户在 prompt() 中输入的任何内容。控制台上的错误是:

UPDATE http://localhost:3030/events/update/5a959fdb9effb926a0594d90 400 (Bad Request)

最佳答案

正如 Kevin 所指出的,您需要在客户端和服务器端将您的操作动词从 UPDATE 更改为 PUT

在服务器端,您需要访问通过 ajax 请求发送的用户输入。如果您已经安装了 bodyparser 中间件,您可以通过 req.body 使用它。

您还重定向了两次。

//client.js    
$(document).ready(function(){
        $('.editEvent').on('click', editEvent);
    });

    function editEvent(){
        var change = prompt('Change to:', '');

            $.ajax({
                type:'PUT',
                url: '/events/update/'+$(this).data('id'),
                data: {event_name: change}
            }).done(function(response){
                console.log(response);
                window.location.replace('http://localhost:3030/');
            }).fail(function(response){
                console.log("Oops not working");
            });
    }

//app.js
app.put('/events/update/:id', function(req,res){
    const data = req.body; 
    db.events.update({_id: ObjectId(req.params.id)}, {$set: data},function(err, result){
        if(err){
            console.log(err);
        }
        res.send('updated successfully');
    });
});

关于javascript - 使用 JQuery、ExpressJS 和 AJAX 更新 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49101809/

相关文章:

javascript - 如何从许多 <p> 中获取特定值

Javascript:使用范围内的范围生成随机数

javascript - jquery ajax post 将我发送到操作页面并且不会显示结果数据

java - 服务器信息未更新

jquery - 在 while 循环中延迟

jquery - 跨域 jQuery Ajax 在 IE9 中不起作用

node.js - 将一个Docker容器中的nodejs应用连接到Docker Swarm上另一个容器中的mongodb

javascript - 设置选择菜单的选定值

javascript - 通过 Meteor/Mongo 返回子文档数组

javascript - Mongo 聚合计数值实例