簡體   English   中英

MEAN Stack無法使用PUT方法更新MongoDB記錄

[英]MEAN Stack Cannot Update MongoDB Record using PUT method

使用PUT方法無法更新mongoDB記錄。 參數正確傳遞,我猜查詢中一定有問題。

架構

let Boards = new mongoose.Schema({
    title: String,
    description: String,
    lastUploaded: Number,
    owner_id: String
});

服務器:

module.exports.updateTime = function (req, res) {
    let board = new Board();
    let id = new mongoose.Types.ObjectId(req.body._id);
    let myquery = { _id: id };
    let newvalues = { lastUploaded: req.body.time };
    console.log("New time: " + req.body.time); //Number recieved
    console.log("Id: " + req.body._id); //String recieved
    board.findByIdAndUpdate(myquery, newvalues, function (err, response) {
        if (err) {
            response = { success: false, message: "Error updating data" };
        } else {
            response = { success: true, message: "Data updated" };
        }
        res.json(response);
    });
    board.close();
};

客戶:

public updateTime(updateOptions: UpdateTime): Observable<any> {
        let headers = new Headers;
        let URI = `${apiUrl}/updateTime`;
        headers.append('Content-Type', 'application/json');
        return this.http.put(URI, updateOptions, { headers: headers })
            .map(this.extractData)
            .catch(this.handleError);
}

路由器:

router.put('/updateTime', ctrlContent.updateTime);

**錯誤圖片**

最后通過.catch(this.handleError);給了我空的響應錯誤.catch(this.handleError);

我可以看到兩個錯誤。

首先, findByIdAndUpdate方法的第一個參數應為_id本身,而不是具有_id屬性的對象:

// this will not work
board.findByIdAndUpdate({ _id: id }, newvalues, handler);

// this is how it should be
board.findByIdAndUpdate(_id, newvalues, handler);

其次,您正在調用board.close(); 在查詢回調之外。 關閉連接可能是一個錯誤,但是即使您絕對需要它,也應該在回調函數中執行它。

這是一個完整的服務器示例:

module.exports.updateTime = function (req, res) {
    let id = req.body._id;
    let newvalues = { lastUploaded: req.body.time };

    Board.findByIdAndUpdate(id, newvalues, function (err, response) {
        if (err) {
            res.json({ success: false, message: "Error updating data" });
        } else {
            res.json({ success: true, message: "Data updated" });
        }
    });
};

暫無
暫無

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

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