[英]MongoDB Atlas/Cloud retrieving data from _id
I am creating a project with MongoDB Atlas/Cloud and I have the method to obtain ALL the data of a database that I have created from the cloud.我正在使用 MongoDB Atlas/Cloud 创建一个项目,并且我有方法从云中获取我创建的数据库的所有数据。
This is how I did it:我是这样做的:
router.get('/', (req, res) => {
// http://localhost:3000/data
client.connect(async err => {
if (await err) {
console.log("Error connecting to MongoDB Cloud:\n\t" + err.toString());
}
console.log("Connected to the DB!");
const collectionData = client.db("myDatabase").collection("data");
try {
const data = await collectionData.find().toArray();
console.log(data);
res.json(data);
} catch (e) {
res.json({message: e});
}
await client.close();
});
});
But I would like to be able to collect each data individually by introducing its _id in the URI.但我希望能够通过在 URI 中引入其 _id 来单独收集每个数据。 This is how I tried to do it:
这就是我尝试这样做的方式:
router.get('/:dataID', (req, res) => {
// http://localhost:3000/data/<ID>
client.connect(async err => {
if (await err) {
console.log("Error connecting to MongoDB Cloud:\n\t" + err.toString());
}
console.log("Connected to the DB!");
const collectionData = client.db("myDatabase").collection("data");
try {
console.log(req.params.dataID); // It works, it prints the _id
const specificData = await collectionData.findById(req.params.dataID).toArray();
console.log(specificData);
res.json(specificData);
} catch (e) {
res.json({message: e});
}
await client.close();
});
});
But it doesn't work.但它不起作用。 I'm retrieving a blank object:
message: {}
.我正在检索一个空白 object:
message: {}
。 I've checked the _id introduced, it's exactly the same as the _id from the mongoDB object that I'm trying to retrieve.我检查了引入的 _id,它与我试图检索的 mongoDB object 中的 _id 完全相同。 What am I doing wrong?
我究竟做错了什么? It should be the
const specificData = await collectionData.findById(req.params.dataID).toArray();
它应该是
const specificData = await collectionData.findById(req.params.dataID).toArray();
but I don't know what to change to make it work right.但我不知道要改变什么才能让它正常工作。
PS: After making a GET petition to the server to /data
, I get the data, but if I try to make another petition after that, I get an MongoDB Error, do anyone know why is this happening? PS:在向服务器发送 GET 请求到
/data
后,我得到了数据,但是如果我在此之后尝试再次请求,我得到一个 MongoDB 错误,有人知道为什么会这样吗? Thank you in advance先感谢您
Solved:解决了:
const specificData = await collectionData.find(req.params.dataID).toArray();
console.log(specificData.get[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.