簡體   English   中英

更新 MongoDB 集合中的 1 個字段(AJAX、Node.js、Express)

[英]Update 1 field in MongoDB collection (AJAX, Node.js, Express)

我正在嘗試修復我的票務系統,但在嘗試更新“票務”集合中的 1 個字段時,我一直遇到問題。 基本上,如果 'closed' 變量等於 0,它是一個開放的票據,如果它等於 1,它是一個關閉的票據。 出於某種原因,它不會正確寫入數據庫並在 AJAX 調用中給我一個錯誤。 請讓我知道如何解決這個問題,非常感謝!

前端

$('.closetick').click(function () {
    id = $(this).val();
    var closed = '1';
    $.ajax({
        method: 'PUT',
        url: '/close-ticket/' + id,
        data: {
            closed: closed
        },
        success: function (data) {
            window
                .location
                .reload('/admin-dashboard');
        },
        error: function () {
            console.log('error');
        }
    })
});

后端

app.put('/close-ticket/:id', isLoggedIn2, function (req, res) {
    var id = new ObjectID(req.params.id);
    var query = {
        _id: id
    }
    var data = {
        closed: req.body.closed
    };
    mongodb.connect(url, function (err, db) {
        var collection = db.collection('tickets');
        if (err) {
            throw err;
        } else {
            var collection = db.collection("tickets");
            collection.findOneAndUpdate({
                _id: query
            }, {
                $set: {
                    closed: data
                }
            }, {
                upsert: true
            }, function (err, doc) {
                if (err) {
                    throw err;
                } else {
                    console.log("Updated");
                }
                db.close();
            });
        }
    });
});

您的方法存在多個問題,很明顯您不了解JavaScript Objects以及如何使用它們。 鑒於您在req.body正確接收數據,以下將完成這項工作,

app.put('/close-ticket/:id', isLoggedIn2, function (req, res) {
    var id = new ObjectID(req.params.id);
    var query = {
        _id: id
    }
    var data = {
        closed: req.body.closed
    };
    mongodb.connect(url, function (err, db) {
        var collection = db.collection('tickets');
        if (err) {
            throw err;
        } else {
            var collection = db.collection("tickets");
            collection.findOneAndUpdate(query, { //issue 1 here
                $set: {
                    closed: data.closed //issue 2 here
                }
            }, {
                upsert: true
            }, function (err, doc) {
                if (err) {
                    res.sendStatus(400) // give a fail response
                    throw err;
                } else {
                    console.log("Updated");
                    res.sendStatus(200) // success response
                }
                db.close();
            });
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM