I am receiving a FInd Cursor object instead of expected document object

Making a GET request to fetch a document from nodejs

using find method by providing _id

code

import clientPromise from "../../../../lib/mongodb"; 

import { ObjectId } from "mongodb";
export default async function handler(req, res)
{
   
    switch (req.method) {
        case 'GET': {
            return findUserById(req, res);
        }
      
        case 'DELETE': {
            return deleteUserById(req, res);
        }
    }
                         
}

 async function findUserById(req, res) 
 {
    let id = ObjectId(req.query.userId)
    console.log(id)
    console.log(`logging this... in api ${req.query.userId}`)
    try {
        
      
      
        //connect to database
        const client = await clientPromise;
        const db = client.db()

        //get details
        const details = await db.collection("users").find({_id:id})
       console.log(JSON.stringify(details))
        if (!details) {
            return res.status(402).json({ error: { message: 'Edit your Profile. No details found' } });
          }

        return res.json({details})

    } catch (error) {
        //return an error
        return res.json({
            message: new Error(error).message,
            success: false
        })
    }
}

response

FindCursor {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  [Symbol(kCapture)]: false,
  [Symbol(topology)]: Topology {
    _events: [Object: null prototype] {
      topologyDescriptionChanged: [Array],
      connectionPoolCreated: [Function (anonymous)],
      connectionPoolClosed: [Function (anonymous)],
      connectionCreated: [Function (anonymous)],
      connectionReady: [Function (anonymous)],
      connectionClosed: [Function (anonymous)],
      connectionCheckOutStarted: [Function (anonymous)],
      connectionCheckOutFailed: [Function (anonymous)],
      connectionCheckedOut: [Function (anonymous)],
      connectionCheckedIn: [Function (anonymous)],
      connectionPoolCleared: [Function (anonymous)],
      commandStarted: [Function (anonymous)],
      commandSucceeded: [Function (anonymous)],
      commandFailed: [Function (anonymous)],
      serverOpening: [Function (anonymous)],
      serverClosed: [Function (anonymous)],
      serverDescriptionChanged: [Function (anonymous)],
      topologyOpening: [Function (anonymous)],
      topologyClosed: [Function (anonymous)],
      error: [Function (anonymous)],
      timeout: [Function (anonymous)],
      close: [Function (anonymous)],
      serverHeartbeatStarted: [Function (anonymous)],
      serverHeartbeatSucceeded: [Function (anonymous)],
      serverHeartbeatFailed: [Function (anonymous)]
    },
    _eventsCount: 25,
    _maxListeners: undefined,
    bson: [Object: null prototype] {
      serialize: [Function: serialize],
      deserialize: [Function: deserialize]
    },
    s: {
      id: 0,
      options: [Object: null prototype],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set(0) {},
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set(0) {},
      detectShardedTopology: [Function: detectShardedTopology],
      detectSrvRecords: [Function: detectSrvRecords],
      srvPoller: [SrvPoller]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque {
      _head: 1,
      _tail: 1,
      _capacity: undefined,
      _capacityMask: 3,
      _list: [Array]
    }
  },
  [Symbol(namespace)]: MongoDBNamespace { db: 'myFirstDatabase', collection: 'users' },
  [Symbol(documents)]: [],
  [Symbol(initialized)]: false,
  [Symbol(closed)]: false,
  [Symbol(killed)]: false,
  [Symbol(options)]: {
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    fieldsAsRaw: {},
    promoteValues: true,
    promoteBuffers: false,
    promoteLongs: true,
    serializeFunctions: false,
    ignoreUndefined: false,
    bsonRegExp: false,
    raw: false,
    enableUtf8Validation: true
  },
  [Symbol(filter)]: {},
  [Symbol(builtOptions)]: {
    raw: false,
    promoteLongs: true,
    promoteValues: true,
    promoteBuffers: false,
    ignoreUndefined: false,
    bsonRegExp: false,
    serializeFunctions: false,
    fieldsAsRaw: {},
    enableUtf8Validation: true,
    writeConcern: WriteConcern { w: 'majority' },
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    }
  }
}

Please do let me know where am I going wrong?

1 Like

I have exactly the same issue, did you find a solution for this?

1 Like

You need to add .toArray() to your call. The problem is mainly on node js side. See example below:

let sitesCol = database.collection("sites");
let site = await sitesCol.find({ name: "udidact.com" }).toArray();

Hopefully that helps.

8 Likes

Thank you for the answer. Quick Start should include this as well.