Only one model in mongoose connection - javascript

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

The only issue I think can be happening with this connection you might be passing a new schema and model that you will see in your object is with that schema. You don't get all schemas from the cloud, the schema being returned is the one that exists with this connection.

Related

Where is io.sockets.adapter.rooms in io of nodejs?

https://stackoverflow.com/a/6727354/462608
The short answer:
io.sockets.adapter.rooms
I analysed io:
The sockets output part from io as shown in that answer contains the following:
sockets:
{ manager: [Circular],
name: '',
sockets: { '210837319844898486': [Object] },
auth: false,
flags: { endpoint: '', exceptions: [] },
_events: { connection: [Function] } },
Where is the adapter? Where are the rooms?
What is the way to find out adapter and rooms from the output of io?
I think you are trying to get room before joining it. First You have to Join room and than you can get the rooms in io.sockets.adapter.rooms You can checkout this link to know rooms
let room_id = 111
io.sockets.on("connection", function (socket) {
// Everytime a client logs in, display a connected message
console.log("Server-Client Connected!");
socket.join("_room" + room_id);
socket.on('connected', function (data) {
});
console.log(io.sockets.adapter.rooms);
socket.on('qr_code_scan', function (room_id) {
io.sockets.in("_room" + room_id).emit("qr_code_scan", true);
});
});
Log of io.sockets.adapter.rooms
{bjYiUV5YZy54VedKAAAA: Room, _room111: Room}
app.js:55
_room111:Room {sockets: {…}, length: 1}
length:1
sockets:{-isBAZIB-Sm3jArgAAAB: true}
-isBAZIB-Sm3jArgAAAB:true
__proto__:Object
__proto__:Object
-isBAZIB-Sm3jArgAAAB:Room {sockets: {…}, length: 1}
length:1
sockets:{-isBAZIB-Sm3jArgAAAB: true}
-isBAZIB-Sm3jArgAAAB:true
__proto__:Object
__proto__:Object
__proto__:Object
For the current version of "socket.io": "^4.1.2",
io.sockets.adapter.rooms
is a Map like this:
Map(2) { 'hgdAp3ghn1RQZk3iAAAD' => Set(1) { 'hgdAp3ghn1RQZk3iAAAD'
}, 'test' => Set(1) { 'hgdAp3ghn1RQZk3iAAAD' } }
when a room already exist, in this case 'test'.
If you invoke it before a room has been created, then it'd be:
Map(1) { 'w2e2Vnav-zmf6pm4AAAD' => Set(1) { 'w2e2Vnav-zmf6pm4AAAD' } }
Thus the long answer is that it depends on the version you are using, and that for version 4.x the room will only be part of the map after an user has joined the room, not before.
I'm not sure what's up with that response. But I can confirm that when I run a basic socket.io example (codesandbox link) using socket.io#2.1.1 and console.log(io) I see the following in my terminal:
Server {
nsps: {
'/': Namespace {
name: '/',
server: [Circular],
sockets: [Object],
connected: [Object],
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter: [Adapter],
_events: [Object: null prototype],
_eventsCount: 1
}
},
parentNsps: Map {},
_path: '/socket.io',
_serveClient: true,
parser: {
protocol: 4,
types: [
'CONNECT',
'DISCONNECT',
'EVENT',
'ACK',
'ERROR',
'BINARY_EVENT',
'BINARY_ACK'
],
CONNECT: 0,
DISCONNECT: 1,
EVENT: 2,
ACK: 3,
ERROR: 4,
BINARY_EVENT: 5,
BINARY_ACK: 6,
Encoder: [Function: Encoder],
Decoder: [Function: Decoder]
},
encoder: Encoder {},
_adapter: [Function: Adapter],
_origins: '*:*',
sockets: Namespace {
name: '/',
server: [Circular],
sockets: { WFrro9MpS4d1nSouAAAA: [Socket] },
connected: { WFrro9MpS4d1nSouAAAA: [Socket] },
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter: Adapter {
nsp: [Circular],
rooms: [Object],
sids: [Object],
encoder: Encoder {}
},
_events: [Object: null prototype] { connection: [Array] },
_eventsCount: 1
},
eio: Server {
clients: { WFrro9MpS4d1nSouAAAA: [Socket] },
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 5000,
pingInterval: 25000,
upgradeTimeout: 10000,
maxHttpBufferSize: 100000000,
transports: [ 'polling', 'websocket' ],
allowUpgrades: true,
allowRequest: [Function: bound ],
cookie: 'io',
cookiePath: '/',
cookieHttpOnly: true,
perMessageDeflate: { threshold: 1024 },
httpCompression: { threshold: 1024 },
initialPacket: [ '0' ],
ws: WebSocketServer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
options: [Object],
[Symbol(kCapture)]: false
},
_events: [Object: null prototype] { connection: [Function: bound ] },
_eventsCount: 1
},
httpServer: Server {
insecureHTTPParser: undefined,
_events: [Object: null prototype] {
connection: [Function: connectionListener],
close: [Function: bound ],
listening: [Function: bound ],
upgrade: [Function],
request: [Function]
},
_eventsCount: 5,
_maxListeners: undefined,
_connections: 2,
_handle: TCP {
reading: false,
onconnection: [Function: onconnection],
[Symbol(owner_symbol)]: [Circular]
},
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
maxHeadersCount: null,
headersTimeout: 60000,
_connectionKey: '6::::8080',
[Symbol(IncomingMessage)]: [Function: IncomingMessage],
[Symbol(ServerResponse)]: [Function: ServerResponse],
[Symbol(kCapture)]: false,
[Symbol(asyncId)]: 6
},
engine: Server {
clients: { WFrro9MpS4d1nSouAAAA: [Socket] },
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 5000,
pingInterval: 25000,
upgradeTimeout: 10000,
maxHttpBufferSize: 100000000,
transports: [ 'polling', 'websocket' ],
allowUpgrades: true,
allowRequest: [Function: bound ],
cookie: 'io',
cookiePath: '/',
cookieHttpOnly: true,
perMessageDeflate: { threshold: 1024 },
httpCompression: { threshold: 1024 },
initialPacket: [ '0' ],
ws: WebSocketServer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
options: [Object],
[Symbol(kCapture)]: false
},
_events: [Object: null prototype] { connection: [Function: bound ] },
_eventsCount: 1
}
}
With the rooms in io.sockets.adapter.rooms.

FindOne() working to return records, but cannot use MongoDB aggregate query (sum records for ids) for Node.js

I have managed to get the connection open to my DB, and to return single records (which took a long time for me to work out how to do!):
MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').findOne({ "Physician_Profile_ID" : {$eq: 346085}}, {projection:
{'Physician_Profile_ID': 1,
'Total_Amount_of_Payment_USDollars': 1,
'Physician_First_Name': 1,
'Physician_Last_Name': 1}
}).then(function(doc) {
if(!doc)
throw new Error('No records found!');
console.log('Here is the record: ')
console.log(doc);
});
});
The issue i'm having is that I want to have another call that is able to aggregate the records on the specified physician_profile_id. I want to perform this shell query:
db.general.aggregate
([{$match:{Physician_Profile_ID: 346085}},
{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}])
How can I translate this into Node.js's dialect? The syntax you use for the Mongo shell isn't translating over
I have tried the following:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
//var o_id = new ObjectID("5b854c781c332b9558cece8d");
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate({$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}).then(function(doc) {
if(!doc)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
It's throwing this error:
throw err;
^
TypeError: db.collection(...).aggregate(...).then is not a function
at /Users/Badger/mongodb_connect.js:35:67
at result (/Users/Badger/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/Users/Badger/node_modules/mongodb/lib/utils.js:406:9)
at err (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5)
at connectCallback (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5)
at process.nextTick (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7)
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
Please can someone help me out, i've been looking for a few hours now and have searched on the site but aren't getting any luck. It's not making sense to me that the error is stating that aggregate isn't a function, when findOne() is. Unless aggregate has to be nested inside of Find(), but this isn't working for me either
Many thanks
Update:
Running this code:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
//var o_id = new ObjectID("5b854c781c332b9558cece8d");
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}], function(err,doc) {
if(err)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});
Is returning output that is not expected:
AggregationCursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'payments.general',
cmd:
{ aggregate: 'general',
pipeline: [ [Object], [Object] ],
cursor: {} },
options:
{ readPreference: ReadPreference { mode: 'primary', tags: undefined },
cursor: {},
promiseLibrary: [Function: Promise],
cursorFactory: { [Function: AggregationCursor] super_: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
disconnectHandler: Store { s: [Object], length: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] } },
topology:
Server {
domain: null,
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
open: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array] },
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v8.12.0, LE' },
s:
{ coreTopology: [Object],
sCapabilities: [Object],
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [Object],
sessions: [],
promiseLibrary: [Function: Promise] } },
cursorState:
{ cursorId: null,
cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
reconnect: true },
logger: Logger { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ maxTimeMS: null,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'payments.general',
cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
options:
{ readPreference: [Object],
cursor: {},
promiseLibrary: [Function: Promise],
cursorFactory: [Object],
disconnectHandler: [Object],
topology: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
monitorCommands: false,
socketOptions: {},
socketTimeout: 360000,
connectionTimeout: 30000,
promiseLibrary: [Function: Promise],
clientInfo: [Object],
read_preference_tags: null,
readPreference: [Object],
dbName: 'admin',
servers: [Array],
server_options: [Object],
db_options: [Object],
rs_options: [Object],
mongos_options: [Object],
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
bson: BSON {} },
promiseLibrary: [Function: Promise],
session: undefined },
sortValue: undefined }
You have to use db.collection('general').aggregate([{}])
when you do .aggregate it will return you a cursor, and with the cursor you can loop cursor.each but what you want to do most of the cases is to transform it into an array.
MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('payments');
db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}]).toArray(function(err,doc) {
if(err)
throw new Error('No records found!');
console.log('Here is the bastard record: ')
console.log(doc);
});
});

How to display the results of MongoDB $near query

So I am running a legacy $near search here
SoundSpot.find(
{ location : { $near : [ longitude, latitude ], $maxDistance: 100 } }
);
But I'm confused on what is actually happening to what I'm finding. To my understanding and research the search will show the documents sorted by location nearest to the given coordinates, but anything that i do to try to see the documents only outputs this large Query. i have no idea what this giant Query means, im not vary familiar with mongo and javascript and i am trying to figure out how exactly i see what the $near did.
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts:
{ bufferCommands: true,
capped: false,
'$wasForceClosed': undefined },
name: 'soundspots',
collectionName: 'soundspots',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
plugins: [Object] },
modelName: 'soundspot',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
discriminators: undefined,
'$appliedMethods': true,
authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function],
'$appliedHooks': true,
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: [Object],
inherits: {},
callQueue: [],
_indexes: [],
methods: [Object],
statics: [Object],
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
s: [Object],
_userProvidedOptions: undefined,
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object], catch: [Function] } },
schema:
Schema {
obj:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object] },
paths:
{ name: [Object],
key: [Object],
'connected.username': [Object],
type: [Object],
'location.type': [Object],
'location.coordinates': [Object],
'location.longitude': [Object],
'location.latitude': [Object],
'playlist.title': [Object],
'playlist.file': [Object],
'playlist.votes': [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Object] },
aliases: {},
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: { connected: true, location: true, playlist: true },
inherits: {},
callQueue: [],
_indexes: [],
methods:
{ setPassword: [Function],
changePassword: [Function],
authenticate: [Function] },
statics:
{ authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function] },
tree:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Function: Number],
id: [Object] },
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
s: { hooks: [Object] },
_userProvidedOptions: undefined,
options:
{ typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: {},
_conditions:
{ location: { '$near': [Object], '$maxDistance': 100 },
_mongooseOption: 'find' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
collectionName: 'soundspots' },
_traceFunction: undefined }
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts:
{ bufferCommands: true,
capped: false,
'$wasForceClosed': undefined },
name: 'soundspots',
collectionName: 'soundspots',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Object],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
plugins: [Object] },
modelName: 'soundspot',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: null,
pass: null,
name: 'user_account',
options: null,
otherDbs: [],
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
_connectionOptions: [Object],
'$initialConnection': [Object],
db: [Object],
client: [Object] },
discriminators: undefined,
'$appliedMethods': true,
authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function],
'$appliedHooks': true,
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: [Object],
inherits: {},
callQueue: [],
_indexes: [],
methods: [Object],
statics: [Object],
tree: [Object],
query: {},
childSchemas: [],
plugins: [Object],
s: [Object],
_userProvidedOptions: undefined,
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
'$init': Promise { [Object], catch: [Function] } },
schema:
Schema {
obj:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object] },
paths:
{ name: [Object],
key: [Object],
'connected.username': [Object],
type: [Object],
'location.type': [Object],
'location.coordinates': [Object],
'location.longitude': [Object],
'location.latitude': [Object],
'playlist.title': [Object],
'playlist.file': [Object],
'playlist.votes': [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Object] },
aliases: {},
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: { connected: true, location: true, playlist: true },
inherits: {},
callQueue: [],
_indexes: [],
methods:
{ setPassword: [Function],
changePassword: [Function],
authenticate: [Function] },
statics:
{ authenticate: [Function],
serializeUser: [Function],
deserializeUser: [Function],
register: [Function],
findByUsername: [Function],
createStrategy: [Function] },
tree:
{ name: [Function: String],
key: [Function: String],
connected: [Object],
type: [Object],
location: [Object],
playlist: [Object],
_id: [Object],
username: [Object],
hash: [Object],
salt: [Object],
__v: [Function: Number],
id: [Object] },
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
s: { hooks: [Object] },
_userProvidedOptions: undefined,
options:
{ typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: {},
_conditions:
{ location: { '$near': [Object], '$maxDistance': 100 },
_mongooseOption: 'find' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'soundspots',
collectionName: 'soundspots',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
collectionName: 'soundspots' },
_traceFunction: undefined }
Whenever you need to apply $geometry queries then don't forget to apply index in your schema like this:
location: {
type: [Number], // <Longitude, Latitude>
index: {
type: '2dsphere',
sparse: false
},
required: true,
},
Without index(2dsphere) you can't use $geoNear and $near in your aggregatation.
For ex:
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
//coordinates: [longitude, latitude]
distanceField: "dist.calculated",
maxDistance: 200, //Meters
includeLocs: "dist.location",
num: 5,
spherical: true
}
}
]);
In above code near find the nearest place from coordinates you requested.
distanceField find the distance in meters and display like this:
"dist" : {
"calculated" : 42107.6268114667, //Meters
"location" : [
-74.167457,
40.3650877
]
}
maxDistance allows you to find location in range of specified distance in meteres.
num is like $limit you can restrict how many data will return.
This is because you're printing the value of the Query object, instead of iterating on the result.
You are using Mongoose, but the issue is the same if you're using the native node driver.
For example, if I have one document in my test collection:
> db.test.find()
{ "_id": 0, "a": 1, "b": 1, "c": 1, "d": 1 }
Now if I run this following code, it will have a similar output to what you saw:
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
db.db('test').collection('test').find({}, function(err, res) {
console.log(res);
});
});
Note that in the code above, I'm printing the res object. The output of the code is:
Cursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Server] },
length: [Getter] },
bson: BSON {},
ns: 'test.test',
cmd:
{ find: 'test.test',
limit: 0,
skip: 0,
query: {},
readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
slaveOk: true },
options:
{ readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
db:
.... many more lines ....
The difference is that instead of a Query object, I see the Cursor object.
Now if I iterate on the res:
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
db.db('test').collection('test').find({}, function(err, res) {
res.forEach(doc => {console.log(doc)});
});
});
It will print the actual document:
{ _id: 0, a: 1, b: 1, c: 1, d: 1 }
Check out Mongoose's page on the Query object for examples in Mongoose.

MongoDB findOne query doesn't return result or undefined

I'm new to node.js and mongo, and I'm trying to use findOne() to retrieve an object from the "quizzes" collection of my database so that I can examine its properties.
I know that the object exists, because in the Mongo shell, a findOne() call gives me this:
> db.quizzes.findOne({ quiz_id:1 })
{
"_id" : ObjectId("5564b0bf28b816e2462b6a1a"),
"quiz_id" : 1
}
In my routes/index.js, I have this:
router.post('/submitanswer', function(req, res) {
var db = req.db;
var quizCollection = db.get('quizzes');
var quiz = quizCollection.findOne({ quiz_id: 1 });
}
A console.log(quizCollection) gives:
{ manager:
{ driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
collections: { quizzes: [Circular] },
options: { safe: true },
_events: {} },
driver:
{ _construct_args: [],
_native:
{ domain: null,
_events: {},
_maxListeners: undefined,
databaseName: 'quizzr',
serverConfig: [Object],
options: [Object],
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: false,
bsonLib: [Object],
bson: [Object],
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Object],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: [Object],
tag: 1432673566484,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [Object] },
_emitter: { domain: null, _events: {}, _maxListeners: 50 },
_state: 2,
_connect_args: [ 'mongodb://localhost:27017/quizzr', [Object] ] },
helper:
{ toObjectID: [Function],
isObjectID: [Function],
id:
{ [Function: ObjectID]
index: 847086,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] } },
name: 'quizzes',
col:
{ _construct_args: [],
_native:
{ db: [Object],
collectionName: 'quizzes',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: [Object],
pkFactory: [Object],
serverCapabilities: undefined },
_emitter: { domain: null, _events: {}, _maxListeners: Infinity },
_state: 2,
_skin_db:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
_collection_args: [ 'quizzes', undefined ],
id:
{ [Function: ObjectID]
index: 847086,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular] },
emitter: { domain: null, _events: {}, _maxListeners: Infinity } },
options: {} }
while a console.log(quiz) gives:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
name: 'quizzes',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'findOne',
opts: { quiz_id: 1, name: 1, fields: {}, safe: true },
domain: null,
_events: { error: [Function], success: [Function] },
_maxListeners: undefined,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { quiz_id: 1 } }
and of course, trying to reference any property of quiz (ex. quiz('quiz_id')) is undefined.
quizCollection.insert() seems to successfully insert an object, so I think I'm getting the right collection. I thought findOne() would return either undefined if it didn't find anything, or an object that fits the criteria, but what I'm printing doesn't seem to be either. How can I retrieve an object?
NodeJS is asynchronous. Some APIs are synchronous, but findOne is an asynchronous one.
findOne has as no return value. You'll get the result passed on your callback. Most APIs return an error as the first argument, which would be undefined if there wasn't an error, and the result of your query/ fs operation/ net operation etc.
Example:
quiz.findOne({quiz_id: 1}, function (err, quiz) {});
This test shows how to query. here

NodeJS, Mongoose, return variable

thanks in advance for your time and answers:
I've been trying to do something that "should" be easy but it's being me crazy.
the objective is to asign the result of a function to a variable that i can use later on a POST to send information to my MongoDB.
I've a model with a document as:
{ "__v" : 0, "_id" : ObjectId("54ad1aa637ce5c566c13d18f"), "num" : 9 }
What i want is to capture this number "num" : 9 to a variable. I created a function that query the mongodb through the model.
function getNum(){
var Num = require('./models/num.js');
var callback = function(){
return function(err, data) {
if(err) {
console.log("error found: " + err);
}
console.log("the number is: " + data.num);
}
};
return Num.findOne({}, callback());
};
then just to test i assign that function to a variable and try to console.log it just to test if the result is fine.
// =====================================
// TESTING ==============================
// =====================================
app.get('/testing',function(req, res, next){
var a = getNum();
console.log(a);
});
My output is:
{ _mongooseOptions: {},
mongooseCollection:
{ collection:
{ db: [Object],
collectionName: 'num',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
pkFactory: [Object],
serverCapabilities: undefined },
opts: { bufferCommands: true, capped: false },
name: 'num',
conn:
{ base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'project',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: {},
db: [Object] },
queue: [],
buffer: false },
model:
{ [Function: model]
base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'Num',
model: [Function: model],
db:
{ base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'project',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: {},
db: [Object] },
discriminators: undefined,
schema:
{ paths: [Object],
subpaths: {},
virtuals: [Object],
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options: [Object],
_events: {} },
options: undefined,
collection:
{ collection: [Object],
opts: [Object],
name: 'num',
conn: [Object],
queue: [],
buffer: false } },
op: 'findOne',
options: {},
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
{ collection:
{ collection: [Object],
opts: [Object],
name: 'num',
conn: [Object],
queue: [],
buffer: false } },
_castError: null }
**the number is: 9**
This is one of the results i can get in other aproaches i get undefined.
Can anyone wonder what can i do to solve this?
Again thanks for your help.
You can't return the result of an asynchronous function like findOne, you need to use callbacks.
So it would need to be rewritten as something like:
function getNum(callback){
var Num = require('./models/num.js');
return Num.findOne({}, callback);
};
app.get('/testing',function(req, res, next){
getNum(function(err, a) {
console.log(a);
});
});

Categories