How can I switch the database after connecting to MySQL in nodejs using connection pool?
I used to use the normal connection with MySQL since it has some issue now I would like to use the connection pooling. But how can I change the database after creating a connection with MySQL?
Here is how I change the database:
conn.changeUser({
database: req.session.dbname
}, function (err) {
if (err) {
console.log(err);
} else {
next();
}
});
But now it shows conn.changeUser is not a function
Here is the method to connect with mysql:
const conn = mysql.createPool({
connectionLimit: 10,
host: config.host,
user: config.user,
password: config.password,
database: 'shaw_elc_gst_13032019'
});
This is the result when I console.log(conn):
Pool {
_events:
[Object: null prototype] {
connection: [Function],
acquire: [Function],
enqueue: [Function],
release: [Function],
error: [Function] },
_eventsCount: 5,
_maxListeners: undefined,
config:
PoolConfig {
acquireTimeout: 10000,
connectionConfig:
ConnectionConfig {
host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'root',
password: '****',
database: 'shaw_elc_gst_13032019',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: [Circular],
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0 },
_acquiringConnections: [],
_allConnections:
[ PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11069,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11067,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11070,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11068,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11071,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11072,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11073,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11074,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11075,
_pool: [Circular] },
PoolConnection {
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
config: [ConnectionConfig],
_socket: [Socket],
_protocol: [Protocol],
_connectCalled: true,
state: 'authenticated',
threadId: 11076,
_pool: [Circular] } ],
_freeConnections: [],
_connectionQueue:
[ [Function],
[Function],
[Function],
[Function],
[Function],
[Function],
[Function],
[Function] ],
_closed: false }
I suggest giving the pooling documentation a thorough read.
You've said you're using conn.changeUser(/*...*/), but then you've said you're using const conn = mysql.createPool(/*...*/); to initialize that conn constant. That means conn is a pool, not a connection; it's not surprising that it doesn't have a changeUser method.
If you want to change database, you need to do it on the connection, not the pool. Instead of using the shorthand pool.query form, you'd do pool.getConnection/conn.changeUser/conn.query/conn.release. First, call your variable pool, not conn:
const pool = mysql.createPool({
then
pool.getConnection(function(err, conn) {
if (err) {
// handle/report error
return;
}
conn.changeUser({
database: req.session.dbname
}, function (err) {
if (err) {
// handle/report error
return;
}
// Use the updated connection here, eventually
// release it:
conn.release();
});
});
That said, if it were me, I'd be more comfortable having a connection pool per database, rather than a common pool where you change the database. That could be pure paranoia on my part, but it's what I'd do. But if you don't use separate pools, I suggest always do the changeUser so you're sure what database you're using, or test thoroughly to see what the mysql module does to handle this (and repeat that testing on every dot release of the module, unless the maintainer documents the behavior).
Related
**I tried passing in a parameter to my route and then passing that parameter to the variable axios with the url. The request succeeds if I remove the params object and instead hardcode the parameter in the url.
I am trying to post the question, but my word is little and the code is too much. I don't know how I can solve this so the explanation is enough to solve the question. I have explained it to the best of my ability. the code can tell much for itself. Thank you.
const axios = require("axios");
dotenv.config();
const Url = "https://api.dhl.com/location-finder/v1/find-by-address";
exports.getLocation = (req, res, next) => {
const country = req.body.countryCode;
axios
.get(Url, {
params: {
countryCode: country}
,headers: {'DHL-API-Key': process.env.LOCATOR_API_KEY}})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
};```
//CODE CONSOLE LOG
**THIS IS THE CONSOLE LOG THE PARAMETER PART IS UNDEFINED HOW WILL I ADD THE PARAMETER
Error: Request failed with status code 400
at createError (/media/ALWI/HACKERFOREVER/MyProjects/JULEYBIB_SHIPPING/server/node_modules/axios/lib/core/createError.js:16:15)
at settle (/media/ALWI/HACKERFOREVER/MyProjects/JULEYBIB_SHIPPING/server/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/media/ALWI/HACKERFOREVER/MyProjects/JULEYBIB_SHIPPING/server/node_modules/axios/lib/adapters/http.js:236:11)
at IncomingMessage.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
config: {
url: 'https://api.dhl.com/location-finder/v1/find-by-address',
method: 'get',
params: { countryCode: undefined },
headers: {
Accept: 'application/json, text/plain, */*',
'DHL-API-Key': '**********************',
'User-Agent': 'axios/0.19.2'
},
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: ClientRequest {
_events: [Object: null prototype] {
socket: [Function],
abort: [Function],
aborted: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 6,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.dhl.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.dhl.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 301,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
connection: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.dhl.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.dhl.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 301,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
_header: 'GET /location-finder/v1/find-by-address HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'DHL-API-Key: *********************\r\n' +
'User-Agent: axios/0.19.2\r\n' +
'Host: api.dhl.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
insecureHTTPParser: undefined,
path: '/location-finder/v1/find-by-address',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular],
responseUrl: 'https://api.dhl.com/location-finder/v1/find-by-address',
redirects: [],
[Symbol(kCapture)]: false
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
_redirectable: Writable {
_writableState: [WritableState],
writable: true,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl: 'https://api.dhl.com/location-finder/v1/find-by-address',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'dhl-api-key': [Array],
'user-agent': [Array],
host: [Array]
}
},
response: {**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
status: 400,
statusText: 'Bad Request',
headers: {
date: 'Mon, 04 May 2020 09:02:52 GMT',
'content-type': 'application/json',
'content-length': '71',
connection: 'close',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'origin,x-requested-with,accept,accept-encoding,content-type,dhl-api-key',
'access-control-max-age': '3628800',
'access-control-allow-methods': 'GET,OPTIONS',
'correlation-id': 'f10a4f9b-0538-4dd5-bdc0-9069f90558ad'
},
config: {
url: 'https://api.dhl.com/location-finder/v1/find-by-address',
method: 'get',
params: [Object],
headers: [Object],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit newTOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
request: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
connection: [TLSSocket],
_header: 'GET /location-finder/v1/find-by-address HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'DHL-API-Key: ****************************\r\n' +
'User-Agent: axios/0.19.2\r\n' +
'Host: api.dhl.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'GET',
insecureHTTPParser: undefined,
path: '/location-finder/v1/find-by-address',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: { error: [Object] }
},
isAxiosError: true,
toJSON: [Function]
}
It is a breaking change from axios version 0.19.
If you would like to add a parameter to a request you have to pass it via an interceptor.
As example:
const axios = require('axios');
// api openexchange
const oexchange = axios.create({
baseURL: 'https://openexchangerates.org/api/',
timeout: parseInt(process.env.TIMEOUTEXTERNALREQUEST)
})
oexchange.interceptors.request.use((config) => {
config.params = config.params || {};
config.params.app_id = process.env.OPENEXCHANGEAPITOKEN // <-- here add the query params in your case it will be countryCode
return config;
});
exports.cotacao = async (req, res) => {
try {
req.oexchange = await oexchange.get('latest.json') //here i'm calling external api with query params added in interceptor
return res.status(200).json(req.oexchange.data)
} catch (e) {
res.status(500).json({errors: [{ location: 'cotacao', msg: 'Houve um erro ao acessar a api do open exchange.', param: 'openexchangerates' }]})
}
}
It is a know behavior that was added in version 0.19 (May 30, 2019)
Currently there is a community effort to fix that behavior you can follow here, it is addressed to be fixed in release 0.20.
If you would like the old way of passing in url params you should use version 0.18 backwards.
Every code here is based in axios documentation
My English is a little bad sorry
I am trying to get all connected clients data
Sample;
var a_sockets = io.sockets.clients();
console.log(a_sockets);
Return ;
Namespace {
name: '/',
server:
Server {
nsps: { '/': [Circular] },
parentNsps: Map {},
_path: '/socket.io',
_serveClient: true,
parser:
{ protocol: 4,
types: [Array],
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: [Circular],
eio:
Server {
clients: [Object],
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 5000,
pingInterval: 25000,
upgradeTimeout: 10000,
maxHttpBufferSize: 100000000,
transports: [Array],
allowUpgrades: true,
allowRequest: [Function: bound ],
cookie: 'io',
cookiePath: '/',
cookieHttpOnly: true,
perMessageDeflate: [Object],
httpCompression: [Object],
initialPacket: [Array],
ws: [WebSocketServer],
_events: [Object],
_eventsCount: 1 },
httpServer:
Server {
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
headersTimeout: 40000,
_connectionKey: '6::::9999',
[Symbol(IncomingMessage)]: [Function],
[Symbol(ServerResponse)]: [Function],
[Symbol(asyncId)]: 5 },
engine:
Server {
clients: [Object],
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 5000,
pingInterval: 25000,
upgradeTimeout: 10000,
maxHttpBufferSize: 100000000,
transports: [Array],
allowUpgrades: true,
allowRequest: [Function: bound ],
cookie: 'io',
cookiePath: '/',
cookieHttpOnly: true,
perMessageDeflate: [Object],
httpCompression: [Object],
initialPacket: [Array],
ws: [WebSocketServer],
_events: [Object],
_eventsCount: 1 } },
sockets:
{ '71kTaZqD9WLFgyC0AAAA':
Socket {
nsp: [Circular],
server: [Server],
adapter: [Adapter],
id: '71kTaZqD9WLFgyC0AAAA',
client: [Client],
conn: [Socket],
rooms: {},
acks: {},
connected: true,
disconnected: false,
handshake: [Object],
fns: [],
flags: {},
_rooms: [],
userId:
'8580af1b5f364c98a20a49185e018412642e92efb79421734881b53e1e1b18b6_t' } },
connected:
{ '71kTaZqD9WLFgyC0AAAA':
Socket {
nsp: [Circular],
server: [Server],
adapter: [Adapter],
id: '71kTaZqD9WLFgyC0AAAA',
client: [Client],
conn: [Socket],
rooms: {},
acks: {},
connected: true,
disconnected: false,
handshake: [Object],
fns: [],
flags: {},
_rooms: [],
**userId:
'8580af1b5f364c98a20a49185e018412642e92efb79421734881b53e1e1b18b6_t'** } },
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter:
Adapter {
nsp: [Circular],
rooms: { '71kTaZqD9WLFgyC0AAAA': [Room] },
sids: { '71kTaZqD9WLFgyC0AAAA': [Object] },
encoder: Encoder {} },
_events: [Object: null prototype] { connection: [Function] },
_eventsCount: 1 }
just want to get userId data.
I want take it [ Connected -> userId ]
So I can compare users
How can I solve this problem?
I apologize again for my english
Thanks.
I would be very happy if you could help me.
I wish you a good day
Short answer(assuming you are using version >=1.0):
var srvSockets = io.sockets.sockets;
Object.keys(srvSockets);
I am using the native node.js mongodb driver, and just did a basic find() operation on a collection and it returned, well, something I don't understand. I don't expect to know everything about this object, just for starters I'd like to know where I should begin to parse this object for my desired collection.
Other interesting facts: I'm using OsX.
Thanks for your concern! I'll include this object below...
Readable {
connection: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'epc.customers',
cmd:
{ find: 'epc.customers',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
options: [Getter],
native_parser: [Getter],
slaveOk: [Getter],
writeConcern: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object] },
_eventsCount: 5,
_maxListeners: undefined,
s:
{ options: [Object],
callbacks: [Object],
logger: [Object],
state: 'connected',
reconnect: true,
reconnectTries: 30,
reconnectInterval: 1000,
emitError: true,
currentReconnectRetry: 30,
ismaster: [Object],
readPreferenceStrategies: undefined,
authProviders: [Object],
id: 1,
tag: undefined,
disconnectHandler: [Object],
wireProtocolHandler: {},
Cursor: [Object],
bsonInstance: {},
bson: {},
pool: [Object],
isMasterLatencyMS: 2,
serverDetails: [Object] },
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
cursorState:
{ cursorId: null,
cmd:
{ find: 'epc.customers',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
callbacks: null,
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'epc.customers',
cmd:
{ find: 'epc.customers',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
s: [Object],
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
topologyOptions:
{ socketOptions: {},
auto_reconnect: true,
host: 'localhost',
port: 27017,
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
disconnectHandler: [Object],
bson: {},
messageHandler: [Function],
wireProtocolHandler: {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
Evening
var MongoClient = require('mongodb').MongoClient
, assert = require('assert')
, ObjectId = require('mongodb').ObjectId;
// Connection URL
var url = 'mongodb://localhost:27017/eProveCommons';
// Use connect method to connect to the Server
var findAll = function(db, callback) {
var collection = db.collection('all');
collection.find().toArray(function(err, docs){
assert.equal(err, null);
console.log(docs);
callback(docs);
})
}
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log('You are connected correctly to the server.');
findAll(db, function(docs){
exports.getAll = function(){
return docs;
}
db.close();
});
});
This is a cursor object.
With the cursor, you would do something like
var cursor = collection.find({});
cursor.each(...);
See this link for more details: https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html
Note: If you know you have a small result set, you can use find({}).toArray() which will return a list of documents.
I am trying to read the output of find function from mongodb connection.
I want to store result of database to JSON/Array called result like :
collection= db.collection('users');
result =collection.find().
Right now with this code in result i am getting some weird long json output:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'askr',
serverConfig:
{ domain: null,
_events: [Object],
_maxListeners: 10,
auth: [Getter],
_callBackStore: [Object],
_commandsStore: [Object],
_dbStore: [Object],
options: [Object],
_serverState: 'connected',
_haProcess: [Object],
servers: [Object],
strategyInstance: [Object],
emitOpen: false,
_state: [Object],
_currentServerChoice: 0,
socketTimeoutMS: [Getter/Setter],
_used: true,
logger: [Object] },
options:
{ read_preference_tags: null,
read_preference: 'primary',
url: 'mongodb://vishal:admin#ds055680.mongolab.com:55680/askr',
native_parser: true,
readPreference: [Object],
safe: false,
w: 1 },
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib:
{ BSON: [Object],
Long: [Object],
ObjectID: [Object],
DBRef: [Object],
Code: [Object],
Timestamp: [Object],
Binary: [Object],
Double: [Object],
MaxKey: [Object],
MinKey: [Object],
Symbol: [Object] },
bson: { promoteLongs: true },
bson_deserializer:
{ Code: [Object],
Symbol: [Object],
BSON: [Object],
DBRef: [Object],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Object],
MinKey: [Object],
MaxKey: [Object],
promoteLongs: true },
bson_serializer:
{ Code: [Object],
Symbol: [Object],
BSON: [Object],
DBRef: [Object],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Object],
MinKey: [Object],
MaxKey: [Object],
promoteLongs: true },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 14533369,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1426645764322,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'askr',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
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: 1426645764322,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
collectionName: 'users',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
pkFactory:
{ [Function: ObjectID]
index: 14533369,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
serverCapabilities: undefined },
selector: {},
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
oplogReplay: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
slaveOk: false,
maxTimeMSValue: undefined,
connection: undefined,
transforms: undefined,
totalNumberOfRecords: 0,
items: [],
cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'askr.users' }
You can simply use:
collection.find().toArray();
db.collection.find returns a Cursor which is
A pointer to the result set of a query. Clients can iterate through a cursor to retrieve results. By default, cursors timeout after 10 minutes of inactivity
Refer : http://docs.mongodb.org/manual/reference/method/db.collection.find
if you want to store result of find() you can iterate over it .
eg.
collection= db.collection('users');
result =collection.find().forEach(function(item){
//here item is record. ie. what you have to do with each record.
})
It returns this, i.e. the collection variable back. So that you can do chain calls:
Person
.find({ occupation: /host/ })
.where('name.last').equals('Ghost')
.where('age').gt(17).lt(66)
.where('likes').in(['vaporizing', 'talking'])
.limit(10)
.sort('-occupation')
.select('name occupation')
.exec(callback);
See examples here.
I'm using passport for authentication, and MongoDB for storage. My problem comes after logging in and trying to access the req.user object. Passing it along to the view, I can see the user has value [object Object], while any fields within that are undefined.
Route:
app.get('/upload', isLoggedIn, function(req, res) {
res.render('upload', {
user : req.user
});
});
View:
<h1>The File Upload Page</h1>
<p>
<%= user %>
<%= user.name %>
<%= user._id %>
</p>
Any ideas?
EDIT:
app.post('/upload', isLoggedIn, function(req, res) {
console.log(JSON.stringify(util.inspect(req.user)));
MongoClient.connect(url, function(err, db) {
db.collection('users', function (err, usersCollection) {
usersCollection.update( { _id : req.user._id }, {$push : { images : 'testVal'} }, function (err) {
if (err) {
console.log('Error adding image to user image array');
}
db.close();
res.send('all done');
});
});
});
});
req.user output:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'meninas',
serverConfig:
{ domain: null,
_events: {},
_maxListeners: 10,
auth: [Getter],
_callBackStore: [Object],
_commandsStore: [Object],
_dbStore: [Object],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
_used: true,
replicasetInstance: null,
emitOpen: false,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
serverCapabilities: [Object],
name: 'localhost:27017',
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'destroyed',
_state: [Object],
recordQueryStats: false,
socketTimeoutMS: [Getter/Setter],
_readPreference: [Object],
db: [Circular],
dbInstances: [Object],
connectionPool: [Object],
isMasterDoc: [Object] },
options:
{ read_preference_tags: null,
read_preference: 'primary',
url: 'mongodb://localhost/meninas',
native_parser: true,
readPreference: [Object],
safe: false,
w: 1 },
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib:
{ BSON: [Object],
Long: [Object],
ObjectID: [Object],
DBRef: [Object],
Code: [Object],
Timestamp: [Object],
Binary: [Object],
Double: [Object],
MaxKey: [Object],
MinKey: [Object],
Symbol: [Object] },
bson: { promoteLongs: true },
bson_deserializer:
{ Code: [Object],
Symbol: [Object],
BSON: [Object],
DBRef: [Object],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Object],
MinKey: [Object],
MaxKey: [Object],
promoteLongs: true },
bson_serializer:
{ Code: [Object],
Symbol: [Object],
BSON: [Object],
DBRef: [Object],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Object],
MinKey: [Object],
MaxKey: [Object],
promoteLongs: true },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 15495053,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: false,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1422844480369,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'meninas',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: true,
bsonLib: [Object],
bson: [Object],
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: false,
commands: [],
logger: [Object],
tag: 1422844480369,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
collectionName: 'users',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
pkFactory:
{ [Function: ObjectID]
index: 15495053,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
serverCapabilities: undefined },
selector: { _id: '54cebe00799372571d6bcb70' },
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
oplogReplay: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
raw: false,
readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
slaveOk: false,
maxTimeMSValue: undefined,
connection: undefined,
totalNumberOfRecords: 0,
items: [],
cursorId: { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'meninas.users' }
POST /upload 200 2181.101 ms - 8