I was trying to get the contents of a document by specifying its _id in the search.
This is my current code:
db.find_listing_by_id("6342e1a22d04b5dcc47d6e0c");
const { MongoClient } = require('mongodb');
const client = new MongoClient(uri);
async find_listing_by_id(_player_id) {
let result = null;
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
result = await client.db("game_data").collection("players").find({ _id: _player_id }).toArray();
console.log(result);
if (result) {
console.log(`Player as found with the id: ${_player_id}`);
console.log(result);
}
else {
console.log(`Player as NOT found with the id: ${_player_id}`);
}
}
catch (e) {
console.log(e);
}
finally {
// Ensures that the client will close when you finish/error
await client.close();
console.log("Disconnected successfully to server");
}
return result;
}
I ran into some problems:
- If I don’t put “toArray ()” at the end of my search query, I get a “FindCursor” instead of documents. It’s normal?
- With my current code, where I search via id, I am returned an empty array. If instead of the_id I search through another existing field (for example {name: “MongoDB”}), I receive the document correctly as a response. Can anyone tell me why? I want to clarify, that even if I receive an empty array as a response, I am still shown the message "Player as found with the id: $ { player_id}", so the query seems to find the associated document correctly …