How to display all entries from my mongodb atlas database using nodejs? - node.js

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()

Related

Unable to retrieve multiple values from database

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();

Retrieve a document query with Email firebase firestore

Code:
At line number 57 I created a route to get the data according to user's email.
But I'm unable to get the specific data that this user added to the database. The response I'm getting is looking like this. I'm stuck here although I followed the instruction that is provided in the firebase firestore documentation.
QuerySnapshot {
_firestore: Firestore {
_authCredentials: FirebaseAuthCredentialsProvider {
authProvider: [Provider],
currentUser: [User],
tokenCounter: 0,
forceRefresh: false,
auth: null,
tokenListener: [Function (anonymous)]
},
_appCheckCredentials: FirebaseAppCheckTokenProvider {
appCheckProvider: [Provider],
forceRefresh: false,
appCheck: null,
tokenListener: [Function (anonymous)]
},
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: FirestoreSettingsImpl {
host: 'firestore.googleapis.com',
ssl: true,
credentials: undefined,
ignoreUndefinedProperties: false,
cacheSizeBytes: 41943040,
experimentalForceLongPolling: false,
experimentalAutoDetectLongPolling: false,
useFetchStreams: true
},
_settingsFrozen: true,
_app: FirebaseAppImpl {
_isDeleted: false,
_options: [Object],
_config: [Object],
_name: '[DEFAULT]',
_automaticDataCollectionEnabled: false,
_container: [ComponentContainer]
},
_databaseId: DatabaseId { projectId: 'parlour-1bcf7', database: '(default)' },
_queue: AsyncQueueImpl {
tail: [Promise],
retryableOps: [],
_isShuttingDown: false,
delayedOperations: [Array],
failure: null,
operationInProgress: true,
skipNonRestrictedTasks: false,
timerIdsToSkip: [],
backoff: [ExponentialBackoff],
visibilityHandler: [Function (anonymous)]
},
_firestoreClient: FirestoreClient {
authCredentials: [FirebaseAuthCredentialsProvider],
appCheckCredentials: [FirebaseAppCheckTokenProvider],
asyncQueue: [AsyncQueueImpl],
databaseInfo: [DatabaseInfo],
user: [User],
clientId: 'Hoh8WrPk3BFhkBsirvQx',
authCredentialListener: [Function (anonymous)],
appCheckCredentialListener: [Function (anonymous)],
offlineComponents: [MemoryOfflineComponentProvider],
onlineComponents: [OnlineComponentProvider]
}
},
_userDataWriter: ExpUserDataWriter {
firestore: Firestore {
_authCredentials: [FirebaseAuthCredentialsProvider],
_appCheckCredentials: [FirebaseAppCheckTokenProvider],
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: [FirestoreSettingsImpl],
_settingsFrozen: true,
_app: [FirebaseAppImpl],
_databaseId: [DatabaseId],
_queue: [AsyncQueueImpl],
_firestoreClient: [FirestoreClient]
}
},
_snapshot: ViewSnapshot {
query: QueryImpl {
path: [ResourcePath],
collectionGroup: null,
explicitOrderBy: [],
filters: [Array],
limit: null,
limitType: 'F',
startAt: null,
endAt: null,
memoizedOrderBy: [Array],
memoizedTarget: [TargetImpl]
},
docs: DocumentSet {
comparator: [Function (anonymous)],
keyedMap: [SortedMap],
sortedSet: [SortedMap]
},
oldDocs: DocumentSet {
comparator: [Function (anonymous)],
keyedMap: [SortedMap],
sortedSet: [SortedMap]
},
docChanges: [],
mutatedKeys: SortedSet { comparator: [Function: comparator], data: [SortedMap] },
fromCache: false,
syncStateChanged: true,
excludesMetadataChanges: false
},
metadata: SnapshotMetadata { hasPendingWrites: false, fromCache: false },
query: Query {
converter: null,
_query: QueryImpl {
path: [ResourcePath],
collectionGroup: null,
explicitOrderBy: [],
filters: [Array],
limit: null,
limitType: 'F',
startAt: null,
endAt: null,
memoizedOrderBy: [Array],
memoizedTarget: [TargetImpl]
},
type: 'query',
firestore: Firestore {
_authCredentials: [FirebaseAuthCredentialsProvider],
_appCheckCredentials: [FirebaseAppCheckTokenProvider],
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: [FirestoreSettingsImpl],
_settingsFrozen: true,
_app: [FirebaseAppImpl],
_databaseId: [DatabaseId],
_queue: [AsyncQueueImpl],
_firestoreClient: [FirestoreClient]
}
}
}
Replace lines 64 to 67 with the following snippet
for (const doc of querySnapshot.docs) {
console.log(doc.id, '=>', doc.data())
}

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.

Deploying Node-expressjs app in lambda - [Error: socket hang up] code: ECONNRESET

I am trying to deploy my Expressjs application into lambda, but i am getting below error. Please try to me to resolve this error.
lambda response:
{
"statusCode": 502,
"body": "",
"headers": {}
}
lambda log (it contains console of mongo connection and error)
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
plugins: [],
models: { Student: [Object] },
modelSchemas: { Student: [Object] },
options: { pluralization: true } },
collections:
{ student:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'student',
collectionName: 'student',
conn: [Circular],
queue: [],
buffer: false,
emitter: [Object] } },
models:
{ Student:
{ [Function: model]
hooks: [Object],
base: [Object],
modelName: 'Student',
model: [Function: model],
db: [Circular],
discriminators: undefined,
schema: [Object],
collection: [Object],
Query: [Object],
'$__insertMany': [Function],
insertMany: [Function] } },
config: { autoIndex: true },
replica: false,
hosts: null,
host: '1.0.0.0.0',
port: 3000,
user: undefined,
pass: undefined,
name: 'sudentdb',
options:
{ mongos: {},
db: { safe: true, forceServerObjectId: false },
auth: {},
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} } },
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db:
EventEmitter {
domain: null,
_events:
{ close: [Function],
error: [Function],
reconnect: [Function],
timeout: [Function],
open: [Function],
parseError: [Function] },
_eventsCount: 6,
_maxListeners: undefined,
s:
{ databaseName: 'studentdb',
dbCache: {},
children: [],
topology: [Object],
options: [Object],
logger: [Object],
bson: {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
_events:
{ connected: [Function],
error: [Function],
disconnected: [Function] },
_eventsCount: 3 }
{ [Error: socket hang up] code: 'ECONNRESET' }
student.model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var studentSchema = new Schema({
name: String,
rollnumber: Number,
},{collection:"student"});
module.exports = mongoose.model('Student', studentSchema);
api/student(REST API - GET method)
exports.index = function(req, res) {
console.log(mongoose.connection)
Student.findOne({},function(err,doc){
if(err){
return res.json("error found");
}else{
return res.json(doc);
}
});
};
lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./bin/www');
const server = awsServerlessExpress.createServer(app);
exports.handler = (event,context)=>{
console.log("EVENT: " + JSON.stringify(event));
awsServerlessExpress.proxy(server,event,context);
}

Resources