Trouble accessing user object fields in Express.js - javascript

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

Related

Parsing nested json with javascript

I have some JSON.
{
ZVH2: {
username: 'ZVH2',
ping: 0,
uuid: '3a4423c3-dce1-40c1-8333-ab2ffdfcd005',
displayName: ChatMessage {
json: [Object],
text: '',
extra: [Array],
bold: undefined,
italic: undefined,
underlined: undefined,
strikethrough: undefined,
obfuscated: undefined,
color: undefined
},
entity: Entity {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
id: 367,
type: 'player',
position: [Vec3],
velocity: [Vec3],
yaw: 3.141592653589793,
pitch: 0,
onGround: false,
height: 1.62,
width: 0,
effects: [Object],
equipment: [Array],
heldItem: [Item],
isValid: true,
metadata: [Array],
username: 'ZVH2',
name: 'player',
timeSinceOnGround: 0,
attributes: [Object],
isInWater: false,
isInLava: false,
isInWeb: undefined,
isCollidedHorizontally: false,
isCollidedVertically: false,
[Symbol(kCapture)]: false
},
gamemode: 2
},
Maximo237354: {
username: 'Maximo237354',
ping: 161,
uuid: 'd6d1bcda-d3c0-406b-b91e-beb3f7be9f5f',
displayName: ChatMessage {
json: [Object],
text: '',
extra: [Array],
bold: undefined,
italic: undefined,
underlined: undefined,
strikethrough: undefined,
obfuscated: undefined,
color: undefined
},
entity: Entity {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
id: 72,
type: 'player',
position: [Vec3],
velocity: [Vec3],
yaw: 2.773437264497239,
pitch: -0.04908738521234035,
onGround: true,
height: 1.62,
width: 0.6,
effects: [Object],
equipment: [Array],
heldItem: [Item],
isValid: true,
metadata: [Array],
name: 'player',
username: 'Maximo237354',
uuid: 'd6d1bcda-d3c0-406b-b91e-beb3f7be9f5f',
dataBlobs: undefined,
attributes: [Object],
headYaw: 2.773437264497239,
[Symbol(kCapture)]: false
}
}
}
I want to use javascript to print the username of username in here. It can either iterate through each thing and print the username value, or it can just take the first value because that is the username too. I can't find a good tutorial online anywhere for this. I want to make sure that I print every username and not entity. Can someone please help with this?
Assuming your JSON variable is called data, you can extract the keys with Object.keys(data)
To iterate and get the usernames you can do
Object.keys(data).forEach(key => {
let username = data[key].username;
});

Switch database in a connection pool in nodejs MySQL

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

Node JS get data io.sockets.clients();

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

What does the MongoClient version of find() actually return?

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.

What is return type of db.collection.find() in mongodb

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.

Categories