Related
I have been trying to make a music system to play songs in vcs using ytdl-core and ytsearcher while using discord js v13 for the bot. But I encounter a long error here it is:
node:events:504
throw er; // Unhandled 'error' event
^
AudioPlayerError: write EPIPE
at afterWriteDispatched (node:internal/stream_base_commons:160:15)
at writevGeneric (node:internal/stream_base_commons:143:3)
at Socket._writeGeneric (node:net:793:11)
at Socket._writev (node:net:802:8)
at doWrite (node:internal/streams/writable:406:12)
at clearBuffer (node:internal/streams/writable:561:5)
at onwrite (node:internal/streams/writable:461:7)
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:106:10)
Emitted 'error' event on AudioPlayer instance at:
at OggDemuxer.onStreamError (E:\_Documents\iobotnew\node_modules\#discordjs\voice\dist\index.js:956:14)
at Object.onceWrapper (node:events:646:26)
at OggDemuxer.emit (node:events:538:35)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
resource: <ref *3> AudioResource {
playStream: OggDemuxer {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: false,
ended: false,
endEmitted: false,
reading: true,
constructed: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: true,
resumeScheduled: false,
errorEmitted: true,
emitClose: true,
autoDestroy: true,
destroyed: true,
errored: Error: write EPIPE
at afterWriteDispatched (node:internal/stream_base_commons:160:15)
at writevGeneric (node:internal/stream_base_commons:143:3)
at Socket._writeGeneric (node:net:793:11)
at Socket._writev (node:net:802:8)
at doWrite (node:internal/streams/writable:406:12)
at clearBuffer (node:internal/streams/writable:561:5)
at onwrite (node:internal/streams/writable:461:7)
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:106:10) {
errno: -4047,
code: 'EPIPE',
syscall: 'write'
},
closed: true,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
dataEmitted: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {
prefinish: [Function: prefinish],
close: [
[Function (anonymous)],
[Function: onclose],
[Function: bound onceWrapper] {
listener: [Function: onFailureCallback]
}
],
end: [
[Function: onend],
[Function: bound onceWrapper] {
listener: [Function: onFailureCallback]
}
],
finish: [
[Function: onfinish],
[Function: bound onceWrapper] {
listener: [Function: onFailureCallback]
}
],
error: [Function: onerror],
readable: [
[Function: bound onceWrapper] {
listener: [Function (anonymous)]
},
[Function: bound onceWrapper] {
listener: [Function: onReadableCallback]
}
]
},
_eventsCount: 6,
_maxListeners: undefined,
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
constructed: true,
prefinished: false,
errorEmitted: true,
emitClose: true,
autoDestroy: true,
errored: Error: write EPIPE
at afterWriteDispatched (node:internal/stream_base_commons:160:15)
at writevGeneric (node:internal/stream_base_commons:143:3)
at Socket._writeGeneric (node:net:793:11)
at Socket._writev (node:net:802:8)
at doWrite (node:internal/streams/writable:406:12)
at clearBuffer (node:internal/streams/writable:561:5)
at onwrite (node:internal/streams/writable:461:7)
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:106:10) {
errno: -4047,
code: 'EPIPE',
syscall: 'write'
},
closed: true,
closeEmitted: false,
[Symbol(kOnFinished)]: []
},
allowHalfOpen: true,
_remainder: null,
_head: null,
_bitstream: null,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
edges: [
<ref *1> {
type: 'ffmpeg ogg',
to: Node {
edges: [ [Object], [Object], [Object] ],
type: 'ogg/opus'
},
cost: 2,
transformer: [Function: transformer],
from: Node { edges: [ [Object], [Circular *1] ], type: 'arbitrary' }
},
<ref *2> {
type: 'ogg/opus demuxer',
to: Node { edges: [ [Object] ], type: 'opus' },
cost: 1,
transformer: [Function: transformer],
from: Node {
edges: [ [Circular *2], [Object], [Object] ],
type: 'ogg/opus'
}
}
],
metadata: null,
volume: undefined,
encoder: undefined,
audioPlayer: <ref *4> AudioPlayer {
_events: [Object: null prototype] { idle: [Function (anonymous)] },
_eventsCount: 1,
_maxListeners: undefined,
_state: {
status: 'buffering',
resource: [Circular *3],
onReadableCallback: [Function: onReadableCallback],
onFailureCallback: [Function: onFailureCallback],
onStreamError: [Function: onStreamError]
},
subscribers: [
PlayerSubscription {
connection: VoiceConnection {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
rejoinAttempts: 0,
_state: [Object],
joinConfig: [Object],
packets: [Object],
receiver: [VoiceReceiver],
debug: null,
onNetworkingClose: [Function: bound onNetworkingClose],
onNetworkingStateChange: [Function: bound onNetworkingStateChange],
onNetworkingError: [Function: bound onNetworkingError],
onNetworkingDebug: [Function: bound onNetworkingDebug],
[Symbol(kCapture)]: false
},
player: [Circular *4]
],
behaviors: { noSubscriber: 'pause', maxMissedFrames: 5 },
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
},
playbackDuration: 0,
started: false,
silencePaddingFrames: 5,
silenceRemaining: -1
}
}
If anyone can help me here is my code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const ytdl = require('ytdl-core');
const { joinVoiceChannel, createAudioResource, createAudioPlayer, AudioPlayerStatus } = require('#discordjs/voice');
const { YTSearcher } = require('ytsearcher');
const searcher = new YTSearcher({
key: "myyoutubeapikey",
revealKey: true
})
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Permet de jouer de la musique dans votre salon vocal !')
.addStringOption(option => option.setName('song').setDescription('Le nom de la musique / URL').setRequired(true)),
async execute(interaction) {
const song = interaction.options.getString('song');
let vc = interaction.member.voice.channel;
if(!vc){
return interaction.reply({ content: ":warning: **- Vous devez ĂȘtre dans un salon vocal pour pouvoir jouer de la musique !**", ephemeral: true });
}
let result = await searcher.search(song, { type: "video" })
console.log(result.first.url)
const stream = ytdl(result.first.url, {
filter: "audioonly",
});
const player = createAudioPlayer();
const resource = createAudioResource(stream);
const connections = joinVoiceChannel({
channelId: vc.id,
guildId: vc.guild.id,
adapterCreator: vc.guild.voiceAdapterCreator,
})
player.play(resource);
connections.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => {
connections.destroy();
});
}
};
I tried a lot of things and I looked before making this post if someone already had the same problem (with the same context)
Try to replace
const stream = ytdl(result.first.url, {
filter: "audioonly",
});
on the
const stream = ytdl(result.first.url, {
filter: "audioonly",
quality: 'highestaudio',
highWaterMark: 1 << 25
});
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).
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