I am using MongoDB for a discord bot I am working on, and I want to retrieve a user's balance. My current code is
function findBalance(id){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("DiscordDB"); var query = { uuid: id }; dbo.collection("players").find(query).toArray(function(err, result) { if (err) throw err; console.log(result.balance); db.close(); }); }); }. When I call the function it returns undefined... any thoughts?
1 Answer
Note the db.collection("players").find(query).toArray() returns an array of documents - these are available as result array. Your code console.log(result.balance) returned undefined - as you are looking for a property called balance in the array. You could do that on an object (or document) which has a property with that name - not on the array.
Retrieve an individual property from an array of objects - do the following to print each document's balance property value:
result.forEach(doc => console.log(doc.balance));
Here is your function's code in a slightly different way:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) throw err;
console.log("Connected successfully to server");
const db = client.db("DiscordDB");
const id = "some value"; // input value
findBalance(db, id, function(result) {
console.log(JSON.stringify(result));
result.forEach(doc => console.log(doc.balance));
console.log("Closing connection.");
client.close();
});
});
const findBalance = function(db, id, callback) {
const query = { uuid: id };
db.collection("players")
.find(query)
.toArray(function(err, result) {
if (err) throw err;
console.log("Query ran okay");
callback(result);
});
};