Home > other >  How to return a value of the most recent document entry in MongoDB
How to return a value of the most recent document entry in MongoDB

Time:08-12

Currently I have a MongoDB with entries that look like this:

{
id: 62f49ecffd9375f8876dffab
channelId: "#username"
stockName: "$USERNAME"
stockPrice: 22
timestamp: "2022-08-11T06:16:47.817Z"
}

located in the database "testDB" and the collection "testColl".

What I am trying to do is find a way to be able to return the value of stockPrice in node.js. Here's the code I'm currently working with:

     if(message === "!debug"){
        console.log(new MongoClient(process.env.MONGO_URL.concat(channel.toString().substring(1))).db(databaseName).collection(collectionName).find().sort('timestamp').limit(1));
     }

where databaseName = "testDB" and collectionName = "testColl". I am quite new with MongoDB so not very familiar with its syntax. Currently when I call this code, I get:


node_modules/tmi.js/lib/logger.js:11
FindCursor {_events: {…}, _eventsCount: 0, _maxListeners: undefined, Symbol(kCapture): false, Symbol(client): MongoClient, …}
_events:
{}
_eventsCount:
0
_maxListeners:
undefined
client:
ƒ client() {\n        return this[kClient];\n    }
closed:
ƒ closed() {\n        return this[kClosed];\n    }
cursorOptions:
ƒ cursorOptions() {\n        return this[kOptions];\n    }
id:
ƒ id() {\n        return this[kId];\n    }
killed:
ƒ killed() {\n        return this[kKilled];\n    }
loadBalanced:
ƒ loadBalanced() {\n        var _a;\n        return !!((_a = this[kClient].topology) === null || _a === void 0 ? void 0 : _a.loadBalanced);\n    }
namespace:
ƒ namespace() {\n        return this[kNamespace];\n    }
readConcern:
ƒ readConcern() {\n        return this[kOptions].readConcern;\n    }
readPreference:
ƒ readPreference() {\n        return this[kOptions].readPreference;\n    }
server:
ƒ server() {\n        return this[kServer];\n    }
session:
ƒ session() {\n        return this[kSession];\n    }
Symbol(builtOptions):
{raw: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, ignoreUndefined: false, …}
Symbol(client):
MongoClient {_events: {…}, _eventsCount: 0, _maxListeners: undefined, s: {…}, Symbol(kCapture): false, …}
Symbol(closed):
false
Symbol(documents):
(0) []
Symbol(filter):
{}
Symbol(initialized):
false
Symbol(kCapture):
false
Symbol(killed):
false
Symbol(namespace):
MongoDBNamespace {db: 'testDB', collection: 'testColl'}
Symbol(options):
{readPreference: ReadPreference, fieldsAsRaw: {…}, promoteValues: true, promoteBuffers: false, promoteLongs: true, …}
Symbol(session):
ClientSession {_events: {…}, _eventsCount: 1, _maxListeners: undefined, client: MongoClient, sessionPool: ServerSessionPool, …}

Also want to add, I may not need to sort my documents since the entries will always be in chronological order but I was trying to use timestamp to sort by the time the entry was placed.

CodePudding user response:

You've got a lot packed into a single line of code. Let's break your console.log value up into several lines, so we can more easily see what's going on.

const channelName = channel.toString().substring(1);
const url = process.env.MONGO_URL.concat(channelName);
const client = new MongoClient(url);
const db = client.db(databaseName);
const collection = db.collection(collectionName);
const cursor = collection.find().sort('timestamp').limit(1);

You are logging cursor.

Looking at the mongodb API documentation for node.js, it looks like you are missing one or two things.

First, you never actually connect to the server (eg, by calling the connect() method). Now, I'm no mongo expert, and it may be that mongo does some cool just-in-time connect-if-not-connected magic when you call a method that requires a connection. If such magic exists, then this is a red herring. But, if not, you'll need to add an await client.connect(); line in there.

Second, to get the value out of the cursor, you need to call a cursor method, like next(). This returns a promise, so you'll need to await the promise in order to log the value.

async function getLatestStockPrice(channel, databaseName, collectionName) {
    const channelName = channel.toString().substring(1);
    const url = process.env.MONGO_URL.concat(channelName);
    const client = new MongoClient(url);
    await client.connect();
    const db = client.db(databaseName);
    const collection = db.collection(collectionName);
    const cursor = collection.find().sort('timestamp').limit(1);
    const item = await cursor.next();
    return item.stockPrice;
}
  • Related