I'm trying to get data by using id but I always get 500
internal error. It would be great help if someone help to find what error I have done to get
request. I have done post request successfully and stored data to MyDatabase
collection of MongoDb Atlas
Here is my code:
app.get("/student/:id", function (req, res) {
db.collection("MyDatabase").findOne(req.params.id, function (err, docs) {
if (err) {
handleError(res, err.message, "Failed to get student record.");
} else {
res.status(200).json(docs);
}
});
});
I have tried:
var ObjectId = require("mongodb").ObjectID;
db.collection("MyDatabase").findOne(
{ _id: new ObjectId(id) }
but still not working
This works for me:
app.get("/student/:id", function (req, res) {
const id = req.params.id;
var o_id = new mongoDB.ObjectID(id);
db.collection("MyDatabase").findOne({ _id: o_id }, function (err, docs) {
if (err) {
handleError(res, err.message, "Failed to get student data.");
} else {
res.status(200).json(docs);
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.