Find() return value problem on NodeJS

I was trying to get the contents of a document by specifying its _id in the search.
This is my current code:

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();
            if (result) {
                console.log(`Player as found with the id: ${_player_id}`);
            else {
                console.log(`Player as NOT found with the id: ${_player_id}`);
        catch (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 …

If you look at the finely written documentation, you will find that indeed this is normal.

Most likely, because the value type of your variable _player_id does not match the value type of the field _id. This or _player_id is really not present in your collection.


Ok, i solved using db.find_listing_by_id(ObjectId("6342e1a22d04b5dcc47d6e0c"));.


So it was the case that

Exactly. Unfortunately I’m new to JS and MongoDB , and hadn’t been careful about using the variable type.
Thanks for your help!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.