用于修改mongodb数组的AJAX帖子

时间:2017-03-06 18:39:32

标签: javascript arrays ajax mongodb post

嘿所以我有一个表格,它是从Mongodb集合“帖子”中生成的。该表列出了用户的日期,时间和奖励,然后显示“选择”按钮。单击选择按钮时,我想更改数据库中该特定帖子的用户数组,并添加单击该帖子的用户的ID。

希望我已经清楚地解释了这个问题,感谢您的帮助或建议。我相信问题出在我的shift.js中的choosePost函数中,但我是AJAX调用的新手,似乎无法弄明白。

这是我的HTML表格

div style="margin:0 -16px" class="row-padding" id="postsToChoose">
                 <table>
                     <thead>
                        <tr>
                            <th><h1> Day  </h1></th>
                            <th><h1> Time </h1></th>
                            <th><h1> Reward </h1></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                 </table>
            </div>

我的shift.js

var studentListData = [];
$(document).ready(function() {
popPostTable();
$('#postsToChoose table tbody').on('click', 'td a.linkChoosePost', choosePost);
});

function popPostTable() {
var tableContent = ''; 
$.getJSON( '/postsToChoose', function( data ) {
    $.each(data, function(){
        studentListData = data;
        tableContent += '<tr>';
        tableContent += '<td>' + this.dayOfTheWeek + '</td>';
        tableContent += '<td>' + this.shiftTime + '</td>';
        tableContent += '<td>' + this.reward + '</td>';
        tableContent += '<td><a href="#" class="linkChoosePost" rel="' + this._id + '">choose</a></td>';
        tableContent += '</tr>';
    });
    $('#postsToChoose table tbody').html(tableContent);
 });
};

function choosePost(event) { 
event.preventDefault();
var confirmation = confirm('Are you sure you want to choose this shift?');
if (confirmation === true) {
    $.ajax({
        type: 'POST',
        url: '/choosePost/' + $(this).attr('rel')
    }).done(function( response ) {
        if (response.msg === '') {
        }
        else {
            alert('Error: ' + response.msg);
        }
        popPostTable();
    });
}
else {
    return false;
}
};

和我的相关index.js

    router.get('/postsToChoose', function(req, res) {
    var db = req.db;
    db.collection('posts').find().toArray(function (err, items) {
        console.log("check for posts"+items);
        res.json(items);
    });
    });
    router.post('/choosePost/:id', function(req, res) { 
    var db = req.db;
    var chosenPost = req.params.id;  
    var userID = req.user._id;
    console.log("USERID: "+ userID);
    console.log("The is the chosen post"+ chosenPost);
    db.collection('posts').update(
        { _id : chosenPost }, //posts._id params.id
        { $set : { 
            "user":userID
        } 
        });

    req.flash('success_msg', 'Post created');
    res.redirect('/hub');
});

帖子模型如下

    {
    "_id" : ObjectId("58b8215e82ea04412d433a48"),
    "user" : [ 
    "1223344vew4683928b",  
    "9484794782bkc00980"
    ],
    "location" : "Dublin",
    "reward" : 300,
    "company" : "Apple",
    "shiftTime" : "day",
    "dayOfTheWeek" : "4",
    "__v" : 0
}

0 个答案:

没有答案