MEAN Stack无法使用PUT方法更新MongoDB记录

时间:2018-07-30 02:40:02

标签: node.js angular mongodb express

无法使用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);

**Error Picture**

最后通过.catch(this.handleError);给了我空的响应错误

1 个答案:

答案 0 :(得分:1)

我可以看到两个错误。

首先,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" });
        }
    });
};