【问题标题】:MEAN Stack Cannot Update MongoDB Record using PUT methodMEAN Stack 无法使用 PUT 方法更新 MongoDB 记录
【发布时间】:2018-07-30 12:44:35
【问题描述】:

无法使用 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);给了我空响应错误

【问题讨论】:

  • 你能贴出put url吗?当您 PUT 时,您是否在 url 中传递了 id ?还有 console.log(req.body)
  • 这看起来不像一个完整的例子。路线在哪里? findByIdAndUpdate 回调中会发生什么?看起来不错。
  • @RobertMoskal 通过浏览器网络检查请求尚未完成。所以它不能通过 findByIdAndUpdate。
  • err 的值是多少?
  • @willmaz console.log(req.body) 给出所有传递的参数,这不是问题。似乎问题出在 findByIdAndUpdate

标签: node.js angular mongodb express


【解决方案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" });
        }
    });
};

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 2016-04-14
    • 2015-08-25
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2018-06-12
    相关资源
    最近更新 更多