Unable to retrieve multiple values from database - node.js

The following data exists in the database:
[
{
"_id": {
"$oid": "628c787de53612aad30021ab"
},
"ticker": "EURUSD",
"dtyyyymmdd": "20030505",
"time": "030000",
"open": "1.12161",
"high": "1.12209",
"low": "1.12161",
"close": "1.12209",
"vol": "561",
"id": 1
},
{
"_id": {
"$oid": "628c787de53612aad30021ac"
},
"ticker": "EURUSD",
"dtyyyymmdd": "20030505",
"time": "030100",
"open": "1.12206",
"high": "1.1225",
"low": "1.12206",
"close": "1.1225",
"vol": "1223",
"id": 2
},
{
"_id": {
"$oid": "628c787de53612aad30021ad"
},
"ticker": "EURUSD",
"dtyyyymmdd": "20030505",
"time": "030200",
"open": "1.12238",
"high": "1.12247",
"low": "1.12225",
"close": "1.12231",
"vol": "816",
"id": 3
}
]
If you pull out a single value, for example, through the command:
.findOne({id: 1});
There are no problems and everything works fine.
The problem occurs when getting multiple values from the base - for example:
.find({ticker:"EURUSD"}));
Such a command produces the following output:
FindCursor {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false,
[Symbol(topology)]: Topology {
_events: [Object: null prototype] {
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)],
topologyDescriptionChanged: [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: undefined,
clusterTime: undefined,
connectionTimers: Set(0) {},
detectShardedTopology: [Function: detectShardedTopology],
detectSrvRecords: [Function: detectSrvRecords]
},
[Symbol(kCapture)]: false,
[Symbol(waitQueue)]: Denque {
_head: 2,
_tail: 2,
_capacity: undefined,
_capacityMask: 3,
_list: [Array]
}
},
[Symbol(namespace)]: MongoDBNamespace { db: 'Trading', collection: 'EUR/USD' },
[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)]: { ticker: 'EURUSD' },
[Symbol(builtOptions)]: {
raw: false,
promoteLongs: true,
promoteValues: true,
promoteBuffers: false,
ignoreUndefined: false,
bsonRegExp: false,
serializeFunctions: false,
fieldsAsRaw: {},
enableUtf8Validation: true,
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined,
maxStalenessSeconds: undefined,
minWireVersion: undefined
}
}
}
Question:
Why is this happening and how to get the needed result?

find return value is a cursor in nodejs, there are several ways on how you can use it to access the data, you can read about them here
The easiest way is to use the .toArray() cursor function which just converts the cursor to an array of documents, like so:
const results = await db.collection.find({ticker:"EURUSD"})).toArray();

Related

How to display all entries from my mongodb atlas database using nodejs?

This is my current code to find all entries from MongoDB atlas.
const { MongoClient } = require("mongodb");
const client = new MongoClient(url);
const dbName = "Chats";
const db = client.db(dbName);
const col = db.collection("Users");
app.post('/chat/enter', (req, res) => {
let newmsg = new DataClass(req.body.name, req.body.textChat);
add(newmsg).catch(console.dir);
res.render(path.join(__dirname + "/index.ejs"),{texts:texts});
})
async function add(x) {
try{
await client.connect();
await col.insertOne({"name":x.name,"textChat":x.msg});
}catch (e) {
console.log(e);
}
}
async function find(){
try{
await client.connect();
const a= await col.find({});
console.log(a);
}catch(e){
console.log(e);
}
}
find();
I want to display all the entries from my atlas database but so far I am getting this gibberish. This problem only arises when I use the find keyword or the output is more than one. findOne is working properly.
The output from the terminal is -
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: 3,
_tail: 3,
_capacity: undefined,
_capacityMask: 3,
_list: [Array]
}
},
[Symbol(namespace)]: MongoDBNamespace { db: 'Chats', 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
}
}
}
Try to initialize the database connection in a separate method:
const { MongoClient } = require("mongodb");
const connectDB = async () => {
try {
const client = new MongoClient(url);
await client.connect()
const dbName = "Chats";
return client.db(dbName);
} catch (e) {
console.log(e)
process.exit(0)
}
}
app.post('/chat/enter', (req, res) => {
let newmsg = new DataClass(req.body.name, req.body.textChat);
add(newmsg).catch(console.dir);
res.render(path.join(__dirname + "/index.ejs"),{texts:texts});
})
async function add(x) {
try{
const db = connectDB();
await db.collection("Users").insertOne({"name":x.name,"textChat":x.msg});
}catch (e) {
console.log(e);
}
}
async function find(){
try{
const db = connectDB();
const a = await db.collection("Users").find({});
console.log(a);
}catch(e){
console.log(e);
}
}
find();
use toArray()
const a= await col.find({}).toArray()

Sum MongoDB column using aggregate - result has no property for the sum

I'm fairly new to MongoDB and Node and I came upon a problem developing a REST API.
The problem comes with the "Aggregate" function not properly returning results. After receiving the HTTP instruction, my API goes to run the specified command, the function that I'm using for this is:
const getDataAsync = async function getDataAsync(data) {
if (enabled !== true) { return {type: "Error", message: "Database not connected"}}
const operand = data.operand;
delete data.operand;
if (operand === "sum"){
clientHandler.collection("Sales2").aggregate([
{"_id": null, "total": {$sum: "Sale Gross Value"}}],
function (err, result) {console.log(result)});
}
}
But "result", gives out some weird data without the property "total". So far, based on other answers, I have tried:
Trying to read result[0] (Returns undefined)
Switching to (...).ToArray() instead of a second argument callback function.
Also, something important to note is that I replaced this line for a findOne (just to check that it is accessing the DB at this point) and returns OK.
Any help is appreciated, I'll dump all the output of log(result) in case someone knows how to interpret it.
PD: I know my code is crappy for an API because it is deeply hardcoded, it's just that I want it to work for this specific case before I try to open it up for a more parametric approach
EDIT: Answering some of the question comments:
I'm using _id: null because I saw it on a tutorial, I tried the query on mongo shell and it works.
I'll add some sample document at the end.
console.log(results):
AggregationCursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: AggregateOperation {
options: { readPreference: [ReadPreference] },
ns: MongoDBNamespace { db: 'Sales', collection: '$cmd' },
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
},
readConcern: undefined,
writeConcern: WriteConcern { w: 'majority' },
explain: false,
fullResponse: true,
target: 'Sales2',
pipeline: [ [Object] ],
hasWriteStage: false,
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: undefined,
ns: 'Sales.$cmd',
namespace: MongoDBNamespace { db: 'Sales', collection: '$cmd' },
cmd: {},
options: {
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
}
},
topology: Server {
_events: [Object: null prototype] {
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
topologyDescriptionChanged: [Function (anonymous)],
joined: [Function (anonymous)],
left: [Function (anonymous)],
ping: [Function (anonymous)],
ha: [Function (anonymous)],
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)],
authenticated: [Function (anonymous)],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array]
},
_eventsCount: 35,
_maxListeners: Infinity,
s: {
coreTopology: [Server],
sCapabilities: null,
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 20,
storeOptions: [Object],
store: [Store],
host: '127.0.0.1',
port: 27017,
options: [Object],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
promiseLibrary: [Function: Promise]
},
[Symbol(kCapture)]: false
},
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined,
reconnect: true
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
Sample document:
{
"_id": {
"$oid": "5f88525a475fc997297fb93f"
},
"Date": {
"$date": "2018-01-01T00:01:00.000Z"
},
"Code": "54",
"Category": "ART._HYGIENIC",
"Name": "BELLA PODPASKI NOVA MAXI 10",
"Quantity": {
"$numberDecimal": "1"
},
"Unit Net Cost": {
"$numberDecimal": "2.66"
},
"Sale Net Cost": {
"$numberDecimal": "2.66"
},
"Unit Net Price": {
"$numberDecimal": "1.85"
},
"Sale Net Price": {
"$numberDecimal": "1.85"
},
"Unit Gross Value": {
"$numberDecimal": "2"
},
"Sale Gross Value": {
"$numberDecimal": "2"
},
"Share in Sales %": {
"$numberDecimal": "0"
},
"Margin %": {
"$numberDecimal": "-43.78"
},
"Unit Margin %": {
"$numberDecimal": "-0.81"
},
"Sell Margin %": {
"$numberDecimal": "-0.81"
},
"Share in Margin %": {
"$numberDecimal": "-0.01"
}
}
So I came up with this query.
db.collection.aggregate([
{
"$group": {
"_id": null,
"total": {
"$sum": "$Sale Gross Value"
}
}
}
])
I have created a mongo playground for this here.
https://mongoplayground.net/p/6nSiotXR960
Disclaimer :not an expert in nodejs :-P
Here is query in nodejs :
clientHandler.collection("Sales2").aggregate([
{'$group': {'_id':null, 'total':{'$sum': "$Sale Gross Value"}}}],
function (err, result) {console.log(result)});
Edit:-
Try this-
clientHandler.collection("Sales2").aggregate([
{'$group': {'_id':null, 'total':{'$sum': "$Sale Gross Value"}}}],
function (err, result) {result.forEach(doc => console.log(doc.total))});
OR this
var aggCursor = clientHandler.collection("Sales2").aggregate([
{'$group': {'_id':null, 'total':{'$sum': "$Sale Gross Value"}}}]);
await aggCursor.forEach(doc => console.log(doc.total))

How can I get the aggregate search value using Mongoose from different Node.js?

I have this mongoose query to get some geoNear value.
const results = await mongoose.connection.db
.collection('placemodels')
.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [89.9741, 21.5112] },
distanceField: 'calcDistance',
maxDistance: 25000,
spherical: true,
},
},
]);
console.log(results);
However, I am receiving
AggregationCursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: false,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: AggregateOperation {
options: { readPreference: [ReadPreference] },
ns: MongoDBNamespace { db: 'test', collection: '$cmd' },
readPreference: ReadPreference { mode: 'primary', tags: undefined },
readConcern: undefined,
writeConcern: WriteConcern { w: 'majority' },
explain: false,
fullResponse: true,
target: 'placemodels',
pipeline: [ [Object] ],
hasWriteStage: false,
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: BSON {},
ns: 'test.$cmd',
namespace: MongoDBNamespace { db: 'test', collection: '$cmd' },
cmd: {},
options: {
readPreference: ReadPreference { mode: 'primary', tags: undefined }
},
topology: NativeTopology {
_events: [Object: null prototype] {
topologyDescriptionChanged: [Array],
authenticated: [Function (anonymous)],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array],
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
joined: [Array],
left: [Function (anonymous)],
ping: [Function (anonymous)],
ha: [Function (anonymous)],
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)],
open: [Function],
reconnectFailed: [Function (anonymous)]
},
_eventsCount: 36,
_maxListeners: Infinity,
s: {
id: 0,
options: [Object],
seedlist: [Array],
state: 'connected',
description: [TopologyDescription],
serverSelectionTimeoutMS: 30000,
heartbeatFrequencyMS: 10000,
minHeartbeatFrequencyMS: 500,
Cursor: [class Cursor extends CoreCursor],
bson: BSON {},
servers: [Map],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
promiseLibrary: [Function: Promise],
credentials: [MongoCredentials],
clusterTime: [Object],
connectionTimers: Set(0) {},
srvPoller: [SrvPoller],
detectTopologyDescriptionChange: [Function (anonymous)]
},
[Symbol(kCapture)]: false,
[Symbol(waitQueue)]: Denque { _head: 0, _tail: 0, _capacityMask: 3, _list: [Array] }
},
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
this result?
I tried to use different queries like .find() and other stuff. Nothing seems to work. How can I get the value from aggregate search? I'd also tried to do query inside of the collection('model', (err, collections) => {---- HERE ----}) and it did not work :(
You need to consume the data from AggregationCursor. One way to do this is:
for (let doc = await results.next(); doc != null; doc = await results.next()) {
console.log(doc);
// process your aggregation result here
}
See the documentation for further details regarding Cursors.

Selection in mongoDb return weird stuff

I have the following selection query:
student.findCourses = (fcallback) => {
global.db.collection('students').find(({}, { "courses.courseName": true, _id: false }), (err, result) => {
if (err) {
var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
console.log(jError)
return fcallback(true, jError)
}
var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
console.log(jOk)
console.log(result);
return fcallback(false, jOk)
})
}
And this is what I get in the console. I get status ok however it seems odd to me the response.
{ status: 'ok', message: 'student.js -> found -> 000' }
Cursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'kea.students',
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: { 'courses.courseName': true, _id: false },
readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
slaveOk: true },
options:
{ readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: Store { s: [Object], length: [Getter] } },
topology:
Server {
domain: null,
_events:
{ reconnect: [Function: reconnectHandler],
reconnectFailed: [Function: reconnectFailedHandler],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function],
timeout: [Function],
error: [Object],
close: [Function],
destroy: [Function: destroyHandler] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: BSON {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1,
serverDescription: [Object],
topologyDescription: [Object] },
ismaster:
{ ismaster: true,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: 2017-11-06T19:51:35.856Z,
maxWireVersion: 5,
minWireVersion: 0,
readOnly: false,
ok: 1 },
lastIsMasterMS: 10,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 657,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null },
initalConnect: false,
wireProtocolHandler: WireProtocol { legacyWireProtocol: WireProtocol {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.4, LE, mongodb-core: 2.1.17' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: Logger { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'kea.students',
cmd:
{ find: 'kea.students',
limit: 0,
skip: 0,
query: [Object],
readPreference: [Object],
slaveOk: true },
options:
{ readPreference: [Object],
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 10,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: [Object],
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
socketTimeout: 360000,
connectionTimeout: 30000,
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: BSON {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
at Module.load (module.js:487:32)
I want to get only the data from the query, which is the following:
{ "courses": [
{
"courseName": "Web-development"
},
{
"courseName": "Databases"
},
{
"courseName": "Interface-Design"
}
]
}
I am not sure if there is something wrong with my query or with the way I am asking for the result?
When I do an insertion indeed I say console.log(JSON.stringify(result.ops)) which gives me only the inserted data, but if I use that for the selection it gives me undefined.
That´s why I am not sure if the query is actually working or you just ask in a different way to get the selected data?
From documentation. find return a cursor
https://docs.mongodb.com/manual/reference/method/db.collection.find/
This is what you see in console
In order to get results you can use toArray
https://docs.mongodb.com/manual/reference/method/cursor.toArray/
global.db.collection('students')
.find(({}, { "courses.courseName": 1, _id: 0}).toArray()
.then((data) => {//you will have your result here})
.catch(err => {//error if something wrong});
or in old way
global.db.collection('students')
.find(({}, { "courses.courseName": 1, _id: 0})
.toArray((err,data) => {//do stuff here});
Hope this helps.

MongoDB (Node.js) find not returning expected result

I am trying to make a find from node to a mongodb server. Here is the code:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db;
var mongoServer = new Server(10.141.74.74, 28019,{auto_reconnect: true, safe:true});
var db = new Db("statusReport", mongoServer, {safe:true});
db.open(function(err,db){
if(!err){
db.collection("status",function(err,collection){
if(!err){
collection.find({}, function(a,b){
console.log(a);
console.log(b);
});
}else{
console.log("ERROR: could not open collection");
}
});
db.close();
}else{
console.log("ERROR: could not open database");
}
});
However, instead of returning data it is returning this:
{ db:
{ domain: null,
_events: { open: [] },
_maxListeners: 10,
databaseName: 'statusReport',
serverConfig:
{ domain: null,
_events: null,
_maxListeners: 10,
host: '10.141.74.74',
port: 28019,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
ssl: false,
slaveOk: undefined,
_used: true,
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
dbInstance: [Circular],
dbInstances: [Object],
connectionPool: [Object],
isMasterDoc: [Object] },
options: { safe: true },
_applicationClosed: false,
native_parser: undefined,
bsonLib:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson: {},
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: true,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
_callBackStore: { domain: null, _events: {}, _maxListeners: 10, _notReplied: {} },
logger: { error: [Function], log: [Function], debug: [Function] },
slaveOk: false,
tag: 1363118044637,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
reaperEnabled: false,
_lastReaperTimestamp: 1363118044637,
retryMiliSeconds: 1000,
numberOfRetries: 60,
reaperInterval: 10000,
reaperTimeout: 30000,
readPreference: undefined },
collection:
{ db:
{ domain: null,
_events: [Object],
_maxListeners: 10,
databaseName: 'statusReport',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
native_parser: undefined,
bsonLib: [Object],
bson: {},
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: true,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
_callBackStore: [Object],
logger: [Object],
slaveOk: false,
tag: 1363118044637,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
reaperEnabled: false,
_lastReaperTimestamp: 1363118044637,
retryMiliSeconds: 1000,
numberOfRetries: 60,
reaperInterval: 10000,
reaperTimeout: 30000,
readPreference: undefined },
collectionName: 'status',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] } },
selector: {},
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
slaveOk: false,
raw: false,
read: 'primary',
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
totalNumberOfRecords: 0,
items: [],
cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'statusReport.status' }
I know there is stuff in there because I can see it using MongoHub. I can also query it there too. What is wrong here?
I also tried doing collection.insert(some data here) and the insert works. Just the find does not.
collection.find(callback) returns the cursor, not the documents. you want to do:
collection.find().toArray(callback)

Resources