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.
I logged my connection and got this:
// Connect to Mongo
const promise = mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false }) // Adding new mongo url parser
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
console.log(promise);
Here' what is logged:
Promise { <pending> }
NativeConnection {
base: Mongoose {
connections: [ [Circular] ],
models: { user: Model { user } },
modelSchemas: { user: [Schema] },
options: { pluralization: true, [Symbol(mongoose:default)]: true },
_pluralize: [Function: pluralize],
Schema: [Function: Schema] {
reserved: [Object: null prototype],
Types: [Object],
ObjectId: [Function]
},
model: [Function],
plugins: [ [Array], [Array], [Array], [Array], [Array] ]
},
collections: {
users: NativeCollection {
collection: null,
Promise: [Function: Promise],
_closed: false,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Circular],
queue: [],
buffer: true,
emitter: [EventEmitter]
}
},
models: { user: Model { user } },
config: { autoIndex: true, useCreateIndex: true, useFindAndModify: false },
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype] {
'0': 'disconnected',
'1': 'connected',
'2': 'connecting',
'3': 'disconnecting',
'99': 'uninitialized',
disconnected: 0,
connected: 1,
connecting: 2,
disconnecting: 3,
uninitialized: 99
},
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
plugins: [],
id: 0,
_listening: false,
_connectionString: 'Sorry, but cannot pass :)',
_connectionOptions: {
useNewUrlParser: true,
useUnifiedTopology: true,
promiseLibrary: [Function: Promise],
driverInfo: { name: 'Mongoose', version: '5.10.3' }
},
client: MongoClient {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: {
url: 'sorry, but cannot pass :)',
options: [Object],
promiseLibrary: [Function: Promise],
dbCache: Map {},
sessions: Set {},
writeConcern: undefined,
namespace: [MongoDBNamespace]
},
[Symbol(kCapture)]: false
},
'$initialConnection': Promise { <pending> },
then: [Function],
catch: [Function],
_events: [Object: null prototype] {
open: [Function: bound onceWrapper] { listener: [Function] }
},
_eventsCount: 1
The problem is that I have three models: post, user and message and because of that I cannot for example upload file with multer for message or post. Why is it happening? It cannot be a problem with my cluster, because I have second database on that cluster in other projects that works( which have implemented the same things, but with correct effect).
The only issue I think can be happening with this connection you might be passing a new schema and model that you will see in your object is with that schema. You don't get all schemas from the cloud, the schema being returned is the one that exists with this connection.
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);
});
});
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");
}
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