[英]Cannot Connect to MongoDB with Bitnami MEAN STACK using Mongoose
[英]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.