When I print
let app = express()
on console it prints like this.
{ [EventEmitter: app]
_events: { mount: [Function: onmount] },
_eventsCount: 1,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
...
}
Inside of code snippet, there is an on: function and etc... so I think this makes me possible to use function on like this app.on(...)
const Grid = require('gridfs-stream');
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
console.log(gfs);
});
But, when I print gfs object on console it prints this.
Here is my example link: https://github.com/qkreltms/mongodb_simple_file_upload_to_db_example/blob/master/app.js
Grid {
db:
Db {
_events:
{ reconnect: [Function], close: [Function], timeout: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
s:
{ databaseName: 'imgSaveTest',
dbCache: {},
children: [],
topology: [Server],
options: [Object],
logger: [Logger],
bson: BSON {},
readPreference: [ReadPreference],
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
mongo:
{ [Function]
MongoError: [Function: MongoError],
MongoNetworkError: [Function: MongoNetworkError],
Admin: [Function: Admin],
MongoClient:
{ [Function: MongoClient] super_: [Function], connect: [Circular] },
Db:
{ [Function: Db]
super_: [Function],
SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces',
SYSTEM_INDEX_COLLECTION: 'system.indexes',
SYSTEM_PROFILE_COLLECTION: 'system.profile',
SYSTEM_USER_COLLECTION: 'system.users',
SYSTEM_COMMAND_COLLECTION: '$cmd',
SYSTEM_JS_COLLECTION: 'system.js' },
Collection: [Function: Collection],
Server: [Function: Server],
ReplSet: [Function: ReplSet],
Mongos: [Function: Mongos],
ReadPreference:
{ [Function: ReadPreference]
PRIMARY: 'primary',
PRIMARY_PREFERRED: 'primaryPreferred',
SECONDARY: 'secondary',
SECONDARY_PREFERRED: 'secondaryPreferred',
NEAREST: 'nearest',
isValid: [Function],
primary: [ReadPreference],
primaryPreferred: [ReadPreference],
secondary: [ReadPreference],
secondaryPreferred: [ReadPreference],
nearest: [ReadPreference] },
GridStore:
{ [Function: GridStore]
DEFAULT_ROOT_COLLECTION: 'fs',
DEFAULT_CONTENT_TYPE: 'binary/octet-stream',
IO_SEEK_SET: 0,
IO_SEEK_CUR: 1,
IO_SEEK_END: 2,
exist: [Function],
list: [Function],
read: [Function],
readlines: [Function],
unlink: [Function] },
Chunk: { [Function: Chunk] DEFAULT_CHUNK_SIZE: 261120 },
Logger:
{ [Function: Logger]
reset: [Function],
currentLogger: [Function],
setCurrentLogger: [Function],
filter: [Function],
setLevel: [Function] },
AggregationCursor:
{ [Function: AggregationCursor] super_: [Function], INIT: 0, OPEN: 1, CLOSED: 2 },
CommandCursor:
{ [Function: CommandCursor] super_: [Function], INIT: 0, OPEN: 1, CLOSED: 2 },
Cursor:
{ [Function: Cursor] super_: [Function], INIT: 0, OPEN: 1, CLOSED: 2, GET_MORE: 3 },
GridFSBucket: { [Function: GridFSBucket] super_: [Function] },
CoreServer:
{ [Function: Server]
super_: [Function],
enableServerAccounting: [Function],
disableServerAccounting: [Function],
servers: [Function] },
CoreConnection:
{ [Function: Connection]
super_: [Function],
enableConnectionAccounting: [Function],
disableConnectionAccounting: [Function],
connections: [Function] },
Binary:
{ [Function: Binary]
BUFFER_SIZE: 256,
SUBTYPE_DEFAULT: 0,
SUBTYPE_FUNCTION: 1,
SUBTYPE_BYTE_ARRAY: 2,
SUBTYPE_UUID_OLD: 3,
SUBTYPE_UUID: 4,
SUBTYPE_MD5: 5,
SUBTYPE_USER_DEFINED: 128,
Binary: [Circular] },
Code: { [Function: Code] Code: [Circular] },
Map: { [Function: Map] Map: [Circular] },
DBRef: { [Function: DBRef] DBRef: [Circular] },
Double: { [Function: Double] Double: [Circular] },
Int32: { [Function: Int32] Int32: [Circular] },
Long:
{ [Function: Long]
fromInt: [Function],
fromNumber: [Function],
fromBits: [Function],
fromString: [Function],
INT_CACHE_: [Object],
TWO_PWR_16_DBL_: 65536,
TWO_PWR_24_DBL_: 16777216,
TWO_PWR_32_DBL_: 4294967296,
TWO_PWR_31_DBL_: 2147483648,
TWO_PWR_48_DBL_: 281474976710656,
TWO_PWR_64_DBL_: 18446744073709552000,
TWO_PWR_63_DBL_: 9223372036854776000,
ZERO: [Long],
ONE: [Long],
NEG_ONE: [Long],
MAX_VALUE: [Long],
MIN_VALUE: [Long],
TWO_PWR_24_: [Long],
Long: [Circular] },
MinKey: { [Function: MinKey] MinKey: [Circular] },
MaxKey: { [Function: MaxKey] MaxKey: [Circular] },
ObjectID:
{ [Function: ObjectID]
index: 4899462,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
ObjectId:
{ [Function: ObjectID]
index: 4899462,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
Symbol: { [Function: Symbol] Symbol: [Circular] },
Timestamp:
{ [Function: Timestamp]
fromInt: [Function],
fromNumber: [Function],
fromBits: [Function],
fromString: [Function],
INT_CACHE_: [Object],
TWO_PWR_16_DBL_: 65536,
TWO_PWR_24_DBL_: 16777216,
TWO_PWR_32_DBL_: 4294967296,
TWO_PWR_31_DBL_: 2147483648,
TWO_PWR_48_DBL_: 281474976710656,
TWO_PWR_64_DBL_: 18446744073709552000,
TWO_PWR_63_DBL_: 9223372036854776000,
ZERO: [Timestamp],
ONE: [Timestamp],
NEG_ONE: [Timestamp],
MAX_VALUE: [Timestamp],
MIN_VALUE: [Timestamp],
TWO_PWR_24_: [Timestamp],
Timestamp: [Circular] },
BSONRegExp: { [Function: BSONRegExp] BSONRegExp: [Circular] },
Decimal128:
{ [Function: Decimal128] fromString: [Function], Decimal128: [Circular] },
connect: [Circular],
instrument: [Function] },
curCol: 'uploads',
_col:
Collection {
s:
{ pkFactory: [Function],
db: [Db],
topology: [Server],
dbName: 'imgSaveTest',
options: [Object],
namespace: 'imgSaveTest.uploads.files',
readPreference: [ReadPreference],
slaveOk: true,
serializeFunctions: undefined,
raw: undefined,
promoteLongs: undefined,
promoteValues: undefined,
promoteBuffers: undefined,
internalHint: null,
collectionHint: null,
name: 'uploads.files',
promiseLibrary: [Function: Promise],
readConcern: undefined,
writeConcern: undefined } } }
gfs.collection('uploads');
You can see that there is no collection function inside it, but it works even it doesn't exist on console.
So the question is where does collection function come from?
Thanks.
In this case
let app = express()
express functions is called and its functions are visible in console when you logged it.
But in this case
const Grid = require('gridfs-stream');
Grid is not yet called and you are checking for function after it is called. Try to console gfs after GFS is called
gfs = Grid(conn.db, mongoose.mongo);
console.log(gfs)
Well I don't know even now why collection function isn't on console but, here is the answer I want to.
link: https://github.com/qkreltms/mongodb_simple_file_upload_to_db_example/blob/master/app.js
Grid.prototype.collection = function (name) {
this.curCol = name || this.curCol || this.mongo.GridStore.DEFAULT_ROOT_COLLECTION;
return this._col = this.db.collection(this.curCol + ".files");
}
Related
https://stackoverflow.com/a/6727354/462608
The short answer:
io.sockets.adapter.rooms
I analysed io:
The sockets output part from io as shown in that answer contains the following:
sockets:
{ manager: [Circular],
name: '',
sockets: { '210837319844898486': [Object] },
auth: false,
flags: { endpoint: '', exceptions: [] },
_events: { connection: [Function] } },
Where is the adapter? Where are the rooms?
What is the way to find out adapter and rooms from the output of io?
I think you are trying to get room before joining it. First You have to Join room and than you can get the rooms in io.sockets.adapter.rooms You can checkout this link to know rooms
let room_id = 111
io.sockets.on("connection", function (socket) {
// Everytime a client logs in, display a connected message
console.log("Server-Client Connected!");
socket.join("_room" + room_id);
socket.on('connected', function (data) {
});
console.log(io.sockets.adapter.rooms);
socket.on('qr_code_scan', function (room_id) {
io.sockets.in("_room" + room_id).emit("qr_code_scan", true);
});
});
Log of io.sockets.adapter.rooms
{bjYiUV5YZy54VedKAAAA: Room, _room111: Room}
app.js:55
_room111:Room {sockets: {…}, length: 1}
length:1
sockets:{-isBAZIB-Sm3jArgAAAB: true}
-isBAZIB-Sm3jArgAAAB:true
__proto__:Object
__proto__:Object
-isBAZIB-Sm3jArgAAAB:Room {sockets: {…}, length: 1}
length:1
sockets:{-isBAZIB-Sm3jArgAAAB: true}
-isBAZIB-Sm3jArgAAAB:true
__proto__:Object
__proto__:Object
__proto__:Object
For the current version of "socket.io": "^4.1.2",
io.sockets.adapter.rooms
is a Map like this:
Map(2) { 'hgdAp3ghn1RQZk3iAAAD' => Set(1) { 'hgdAp3ghn1RQZk3iAAAD'
}, 'test' => Set(1) { 'hgdAp3ghn1RQZk3iAAAD' } }
when a room already exist, in this case 'test'.
If you invoke it before a room has been created, then it'd be:
Map(1) { 'w2e2Vnav-zmf6pm4AAAD' => Set(1) { 'w2e2Vnav-zmf6pm4AAAD' } }
Thus the long answer is that it depends on the version you are using, and that for version 4.x the room will only be part of the map after an user has joined the room, not before.
I'm not sure what's up with that response. But I can confirm that when I run a basic socket.io example (codesandbox link) using socket.io#2.1.1 and console.log(io) I see the following in my terminal:
Server {
nsps: {
'/': Namespace {
name: '/',
server: [Circular],
sockets: [Object],
connected: [Object],
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter: [Adapter],
_events: [Object: null prototype],
_eventsCount: 1
}
},
parentNsps: Map {},
_path: '/socket.io',
_serveClient: true,
parser: {
protocol: 4,
types: [
'CONNECT',
'DISCONNECT',
'EVENT',
'ACK',
'ERROR',
'BINARY_EVENT',
'BINARY_ACK'
],
CONNECT: 0,
DISCONNECT: 1,
EVENT: 2,
ACK: 3,
ERROR: 4,
BINARY_EVENT: 5,
BINARY_ACK: 6,
Encoder: [Function: Encoder],
Decoder: [Function: Decoder]
},
encoder: Encoder {},
_adapter: [Function: Adapter],
_origins: '*:*',
sockets: Namespace {
name: '/',
server: [Circular],
sockets: { WFrro9MpS4d1nSouAAAA: [Socket] },
connected: { WFrro9MpS4d1nSouAAAA: [Socket] },
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter: Adapter {
nsp: [Circular],
rooms: [Object],
sids: [Object],
encoder: Encoder {}
},
_events: [Object: null prototype] { connection: [Array] },
_eventsCount: 1
},
eio: Server {
clients: { WFrro9MpS4d1nSouAAAA: [Socket] },
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 5000,
pingInterval: 25000,
upgradeTimeout: 10000,
maxHttpBufferSize: 100000000,
transports: [ 'polling', 'websocket' ],
allowUpgrades: true,
allowRequest: [Function: bound ],
cookie: 'io',
cookiePath: '/',
cookieHttpOnly: true,
perMessageDeflate: { threshold: 1024 },
httpCompression: { threshold: 1024 },
initialPacket: [ '0' ],
ws: WebSocketServer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
options: [Object],
[Symbol(kCapture)]: false
},
_events: [Object: null prototype] { connection: [Function: bound ] },
_eventsCount: 1
},
httpServer: Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
connection: [Function: connectionListener],
close: [Function: bound ],
listening: [Function: bound ],
upgrade: [Function],
request: [Function]
},
_eventsCount: 5,
_maxListeners: undefined,
_connections: 2,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner_symbol)]: [Circular]
},
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
maxHeadersCount: null,
headersTimeout: 60000,
_connectionKey: '6::::8080',
[Symbol(IncomingMessage)]: [Function: IncomingMessage],
[Symbol(ServerResponse)]: [Function: ServerResponse],
[Symbol(kCapture)]: false,
[Symbol(asyncId)]: 6
},
engine: Server {
clients: { WFrro9MpS4d1nSouAAAA: [Socket] },
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 5000,
pingInterval: 25000,
upgradeTimeout: 10000,
maxHttpBufferSize: 100000000,
transports: [ 'polling', 'websocket' ],
allowUpgrades: true,
allowRequest: [Function: bound ],
cookie: 'io',
cookiePath: '/',
cookieHttpOnly: true,
perMessageDeflate: { threshold: 1024 },
httpCompression: { threshold: 1024 },
initialPacket: [ '0' ],
ws: WebSocketServer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
options: [Object],
[Symbol(kCapture)]: false
},
_events: [Object: null prototype] { connection: [Function: bound ] },
_eventsCount: 1
}
}
With the rooms in io.sockets.adapter.rooms.
In my puppeteer/javascript code below I am receiving a different result to what is expected. I am not sure why?
I am expecting the "myjson" value to be returned inside of the "price_json" however it is returning all the elements from the browser as you can see from the actual result.
I'm not sure If I'm missing basic javascript knowledge here however I've done the same thing with a page.evaluate and that seems to be working fine....
Code -
const price_json = await page.on('response', async (response, i) => {
const myjson = await response.json();
console.log("inside of the page.on")
console.log(myjson)
console.log("inside (end) of the page.on")
return myjson
}, i);
console.log(price_json)
Expected Result - (myjson looks like this)
{ unit_price: '$39.65',
carton_price: '$237.92',
stock_code: '66121' }
Actual Result - (price_json after the return...)
_events: [Object: null prototype] { response: [AsyncFunction] },
_eventsCount: 1,
_maxListeners: undefined,
_closed: false,
_client:
CDPSession {
_events:
[Object: null prototype] {
'Fetch.requestPaused': [Function: bound _onRequestPaused],
'Fetch.authRequired': [Function: bound _onAuthRequired],
'Network.requestWillBeSent': [Function: bound _onRequestWillBeSent],
'Network.requestServedFromCache': [Function: bound _onRequestServedFromCache],
'Network.responseReceived': [Function: bound _onResponseReceived],
'Network.loadingFinished': [Function: bound _onLoadingFinished],
'Network.loadingFailed': [Function: bound _onLoadingFailed],
'Page.frameAttached': [Function],
'Page.frameNavigated': [Function],
'Page.navigatedWithinDocument': [Function],
'Page.frameDetached': [Function],
'Page.frameStoppedLoading': [Function],
'Runtime.executionContextCreated': [Function],
'Runtime.executionContextDestroyed': [Function],
'Runtime.executionContextsCleared': [Function],
'Page.lifecycleEvent': [Function],
'Target.attachedToTarget': [Function],
'Target.detachedFromTarget': [Function],
'Page.domContentEventFired': [Function],
'Page.loadEventFired': [Function],
'Runtime.consoleAPICalled': [Function],
'Runtime.bindingCalled': [Function],
'Page.javascriptDialogOpening': [Function],
'Runtime.exceptionThrown': [Function],
'Inspector.targetCrashed': [Function],
'Performance.metrics': [Function],
'Log.entryAdded': [Function],
'Page.fileChooserOpened': [Function] },
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection:
Connection {
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_url:
'ws://127.0.0.1:58923/devtools/browser/89cbedaf-2ce2-4df8-b52b-3836987b2521',
_lastId: 87,
_callbacks: Map {},
_delay: 0,
_transport: [WebSocketTransport],
_sessions: [Map],
_closed: false },
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_target:
Target {
_targetInfo:
{ targetId: 'FB19D7C032DE5773F35827E7AECD9082',
type: 'page',
title: 'https://www.****.com.au/customers/orders',
url: 'https://www.*****.com.au/customers/orders',
attached: true,
browserContextId: '10EE70BFE005227DB58E3291908CB868' },
_browserContext:
BrowserContext {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_connection: [Connection],
_browser: [Browser],
_id: null },
_targetId: 'FB19D7C032DE5773F35827E7AECD9082',
_sessionFactory: [Function],
_ignoreHTTPSErrors: false,
_defaultViewport: { width: 800, height: 600 },
_screenshotTaskQueue: TaskQueue { _chain: [Promise] },
_pagePromise: Promise { [Circular] },
_workerPromise: null,
_initializedCallback: [Function],
_initializedPromise: Promise { true },
_closedCallback: [Function],
_isClosedPromise: Promise { <pending> },
_isInitialized: true },
_keyboard:
Keyboard {
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_modifiers: 0,
_pressedKeys: Set {} },
_mouse:
Mouse {
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_keyboard:
Keyboard { _client: [CDPSession], _modifiers: 0, _pressedKeys: Set {} },
_x: 1157.59375,
_y: 422.09375,
_button: 'none' },
_timeoutSettings:
TimeoutSettings { _defaultTimeout: null, _defaultNavigationTimeout: null },
_touchscreen:
Touchscreen {
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_keyboard:
Keyboard { _client: [CDPSession], _modifiers: 0, _pressedKeys: Set {} } },
_accessibility:
Accessibility {
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' } },
_frameManager:
FrameManager {
_events:
[Object: null prototype] {
[Symbol(Events.FrameManager.FrameAttached)]: [Function],
[Symbol(Events.FrameManager.FrameDetached)]: [Function],
[Symbol(Events.FrameManager.FrameNavigated)]: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_page: [Circular],
_networkManager:
NetworkManager {
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_client: [CDPSession],
_ignoreHTTPSErrors: false,
_frameManager: [Circular],
_requestIdToRequest: [Map],
_requestIdToRequestWillBeSentEvent: Map {},
_extraHTTPHeaders: {},
_offline: false,
_credentials: null,
_attemptedAuthentications: Set {},
_userRequestInterceptionEnabled: false,
_protocolRequestInterceptionEnabled: false,
_userCacheDisabled: false,
_requestIdToInterceptionId: Map {} },
_timeoutSettings:
TimeoutSettings { _defaultTimeout: null, _defaultNavigationTimeout: null },
_frames: Map { 'FB19D7C032DE5773F35827E7AECD9082' => [Frame] },
_contextIdToContext: Map { 5 => [ExecutionContext], 6 => [ExecutionContext] },
_isolatedWorlds: Set { '__puppeteer_utility_world__' },
_mainFrame:
Frame {
_frameManager: [Circular],
_client: [CDPSession],
_parentFrame: null,
_url: 'https://www.*****.com.au/customers/orders',
_id: 'FB19D7C032DE5773F35827E7AECD9082',
_detached: false,
_loaderId: 'D87D50CD254B4D51BD687A720F36BFCA',
_lifecycleEvents: [Set],
_mainWorld: [DOMWorld],
_secondaryWorld: [DOMWorld],
_childFrames: Set {},
_name: undefined,
_navigationURL: 'https://www.*******.com.au/customers/orders' } },
_emulationManager:
EmulationManager {
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_emulatingMobile: false,
_hasTouch: false },
_tracing:
Tracing {
_client:
CDPSession {
_events: [Object],
_eventsCount: 28,
_maxListeners: undefined,
_callbacks: Map {},
_connection: [Connection],
_targetType: 'page',
_sessionId: '45363630A29A7F3799E8612DDB0C79B9' },
_recording: false,
_path: '' },
_pageBindings: Map {},
_coverage:
Coverage {
_jsCoverage:
JSCoverage {
_client: [CDPSession],
_enabled: false,
_scriptURLs: Map {},
_scriptSources: Map {},
_eventListeners: [],
_resetOnNavigation: false },
_cssCoverage:
CSSCoverage {
_client: [CDPSession],
_enabled: false,
_stylesheetURLs: Map {},
_stylesheetSources: Map {},
_eventListeners: [],
_resetOnNavigation: false } },
_javascriptEnabled: true,
_viewport: { width: 1920, height: 1080 },
_screenshotTaskQueue:
TaskQueue {
_chain:
Promise {
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 80 00 00 04 38 08 06 00 00 00 e8 d3 c1 43 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 20 00 ... > } },
_workers: Map {},
_fileChooserInterceptionIsDisabled: false,
_fileChooserInterceptors: Set {} }
I realize this is 2 years old and hopefully you found the answer. Seeing that this has over a hundred views so far...
What you have in the second console.log is the page object itself and not the response. You'll want to do a closure if you want the response in the upper scope, like:
let price_json;
await page.on('response', async (response, i) => {
price_json = await response.json();
}, i);
console.log(price_json);
I have managed to get the connection open to my DB, and to return single records (which took a long time for me to work out how to do!):
MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').findOne({ "Physician_Profile_ID" : {$eq: 346085}}, {projection:
{'Physician_Profile_ID': 1,
'Total_Amount_of_Payment_USDollars': 1,
'Physician_First_Name': 1,
'Physician_Last_Name': 1}
}).then(function(doc) {
if(!doc)
throw new Error('No records found!');
console.log('Here is the record: ')
console.log(doc);
});
});
The issue i'm having is that I want to have another call that is able to aggregate the records on the specified physician_profile_id. I want to perform this shell query:
db.general.aggregate
([{$match:{Physician_Profile_ID: 346085}},
{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}])
How can I translate this into Node.js's dialect? The syntax you use for the Mongo shell isn't translating over
I have tried the following:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
//var o_id = new ObjectID("5b854c781c332b9558cece8d");
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate({$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}).then(function(doc) {
if(!doc)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
It's throwing this error:
throw err;
^
TypeError: db.collection(...).aggregate(...).then is not a function
at /Users/Badger/mongodb_connect.js:35:67
at result (/Users/Badger/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/Users/Badger/node_modules/mongodb/lib/utils.js:406:9)
at err (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5)
at connectCallback (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5)
at process.nextTick (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7)
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
Please can someone help me out, i've been looking for a few hours now and have searched on the site but aren't getting any luck. It's not making sense to me that the error is stating that aggregate isn't a function, when findOne() is. Unless aggregate has to be nested inside of Find(), but this isn't working for me either
Many thanks
Update:
Running this code:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
//var o_id = new ObjectID("5b854c781c332b9558cece8d");
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}], function(err,doc) {
if(err)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
Is returning output that is not expected:
AggregationCursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'payments.general',
cmd:
{ aggregate: 'general',
pipeline: [ [Object], [Object] ],
cursor: {} },
options:
{ readPreference: ReadPreference { mode: 'primary', tags: undefined },
cursor: {},
promiseLibrary: [Function: Promise],
cursorFactory: { [Function: AggregationCursor] super_: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
disconnectHandler: Store { s: [Object], length: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] } },
topology:
Server {
domain: null,
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array] },
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v8.12.0, LE' },
s:
{ coreTopology: [Object],
sCapabilities: [Object],
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [Object],
sessions: [],
promiseLibrary: [Function: Promise] } },
cursorState:
{ cursorId: null,
cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
reconnect: true },
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,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ maxTimeMS: null,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'payments.general',
cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
options:
{ readPreference: [Object],
cursor: {},
promiseLibrary: [Function: Promise],
cursorFactory: [Object],
disconnectHandler: [Object],
topology: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
monitorCommands: false,
socketOptions: {},
socketTimeout: 360000,
connectionTimeout: 30000,
promiseLibrary: [Function: Promise],
clientInfo: [Object],
read_preference_tags: null,
readPreference: [Object],
dbName: 'admin',
servers: [Array],
server_options: [Object],
db_options: [Object],
rs_options: [Object],
mongos_options: [Object],
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
bson: BSON {} },
promiseLibrary: [Function: Promise],
session: undefined },
sortValue: undefined }
You have to use db.collection('general').aggregate([{}])
when you do .aggregate it will return you a cursor, and with the cursor you can loop cursor.each but what you want to do most of the cases is to transform it into an array.
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}]).toArray(function(err,doc) {
if(err)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
I am trying to get data from mongoDB while connecting to server .i inserted one value in mongoDB like this
> use abc
switched to db abc
> db.ac.insert({name:"naveen"})
WriteResult({ "nInserted" : 1 })
> show collections
ac
system.indexes
And try to get that value like this
var express=require('express');
var app =express();
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
app.get('/',function(req,res){
console.log("Connected to server.");
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var collection = db.collection('ac');
console.log(collection)
console.log("Connected correctly to server.");
db.close();
});
})
var url = 'mongodb://localhost:27017/abc';
app.listen(3000,function(){
console.log('server is runninngn')
})
I am getting this error why ?
MacBook-Pro:expressjs naveenkumar$ node index.js
server is runninngn
Connected to server.
{ s:
{ pkFactory:
{ [Function: ObjectID]
index: 462263,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
db:
{ domain: null,
_events: {},
_maxListeners: 10,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
options: [Getter],
native_parser: [Getter],
slaveOk: [Getter],
writeConcern: [Getter] },
topology:
{ domain: null,
_events: [Object],
_maxListeners: 10,
s: [Object],
bson: [Getter],
isMasterDoc: [Getter],
poolSize: [Getter],
autoReconnect: [Getter],
host: [Getter],
port: [Getter],
emitOpen: false,
connectTimeoutMS: 30000,
socketTimeoutMS: 0 },
dbName: 'abc',
options: { promiseLibrary: [Object], readConcern: undefined },
namespace: 'abc.ac',
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
raw: undefined,
slaveOk: true,
serializeFunctions: undefined,
internalHint: null,
collectionHint: null,
name: 'ac',
promiseLibrary:
{ [Function: lib$es6$promise$promise$$Promise]
all: [Function: lib$es6$promise$promise$all$$all],
race: [Function: lib$es6$promise$promise$race$$race],
resolve: [Function: lib$es6$promise$promise$resolve$$resolve],
reject: [Function: lib$es6$promise$promise$reject$$reject] },
readConcern: undefined } }
Connected correctly to server.
Connected to server.
{ s:
{ pkFactory:
{ [Function: ObjectID]
index: 462263,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
db:
{ domain: null,
_events: {},
_maxListeners: 10,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
options: [Getter],
native_parser: [Getter],
slaveOk: [Getter],
writeConcern: [Getter] },
topology:
{ domain: null,
_events: [Object],
_maxListeners: 10,
s: [Object],
bson: [Getter],
isMasterDoc: [Getter],
poolSize: [Getter],
autoReconnect: [Getter],
host: [Getter],
port: [Getter],
emitOpen: false,
connectTimeoutMS: 30000,
socketTimeoutMS: 0 },
dbName: 'abc',
options: { promiseLibrary: [Object], readConcern: undefined },
namespace: 'abc.ac',
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
raw: undefined,
slaveOk: true,
serializeFunctions: undefined,
internalHint: null,
collectionHint: null,
name: 'ac',
promiseLibrary:
{ [Function: lib$es6$promise$promise$$Promise]
all: [Function: lib$es6$promise$promise$all$$all],
race: [Function: lib$es6$promise$promise$race$$race],
resolve: [Function: lib$es6$promise$promise$resolve$$resolve],
reject: [Function: lib$es6$promise$promise$reject$$reject] },
readConcern: undefined } }
**Connected correctly to server.**
Please why it is giving error
If you want to display all the documents in the given collection the code should be like this :
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var collection = db.collection('ac').find({},function(err,doc){
if(err)
throw err;
else{
console.log(doc);
}
});
console.log("Connected correctly to server.");
db.close();
});
this will print all the documents of collection ac. Otherwise if you directly try to print collection all the metadata will also get printed.
I'm new to node.js and mongo, and I'm trying to use findOne() to retrieve an object from the "quizzes" collection of my database so that I can examine its properties.
I know that the object exists, because in the Mongo shell, a findOne() call gives me this:
> db.quizzes.findOne({ quiz_id:1 })
{
"_id" : ObjectId("5564b0bf28b816e2462b6a1a"),
"quiz_id" : 1
}
In my routes/index.js, I have this:
router.post('/submitanswer', function(req, res) {
var db = req.db;
var quizCollection = db.get('quizzes');
var quiz = quizCollection.findOne({ quiz_id: 1 });
}
A console.log(quizCollection) gives:
{ manager:
{ driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
collections: { quizzes: [Circular] },
options: { safe: true },
_events: {} },
driver:
{ _construct_args: [],
_native:
{ domain: null,
_events: {},
_maxListeners: undefined,
databaseName: 'quizzr',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: false,
bsonLib: [Object],
bson: [Object],
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: [Object],
tag: 1432673566484,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
_emitter: { domain: null, _events: {}, _maxListeners: 50 },
_state: 2,
_connect_args: [ 'mongodb://localhost:27017/quizzr', [Object] ] },
helper:
{ toObjectID: [Function],
isObjectID: [Function],
id:
{ [Function: ObjectID]
index: 847086,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] } },
name: 'quizzes',
col:
{ _construct_args: [],
_native:
{ db: [Object],
collectionName: 'quizzes',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: [Object],
pkFactory: [Object],
serverCapabilities: undefined },
_emitter: { domain: null, _events: {}, _maxListeners: Infinity },
_state: 2,
_skin_db:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
_collection_args: [ 'quizzes', undefined ],
id:
{ [Function: ObjectID]
index: 847086,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
emitter: { domain: null, _events: {}, _maxListeners: Infinity } },
options: {} }
while a console.log(quiz) gives:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
name: 'quizzes',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'findOne',
opts: { quiz_id: 1, name: 1, fields: {}, safe: true },
domain: null,
_events: { error: [Function], success: [Function] },
_maxListeners: undefined,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { quiz_id: 1 } }
and of course, trying to reference any property of quiz (ex. quiz('quiz_id')) is undefined.
quizCollection.insert() seems to successfully insert an object, so I think I'm getting the right collection. I thought findOne() would return either undefined if it didn't find anything, or an object that fits the criteria, but what I'm printing doesn't seem to be either. How can I retrieve an object?
NodeJS is asynchronous. Some APIs are synchronous, but findOne is an asynchronous one.
findOne has as no return value. You'll get the result passed on your callback. Most APIs return an error as the first argument, which would be undefined if there wasn't an error, and the result of your query/ fs operation/ net operation etc.
Example:
quiz.findOne({quiz_id: 1}, function (err, quiz) {});
This test shows how to query. here