Mongoose/MongoDB won't connect from Node.js - node.js

So i'm new to MongoDB/Mongoose, I am following many different tutorials online about how to connect my node.js server to mongodb using mongoose, however none of them seem to mention the issue i'm having. I have mongo server running on my machine, I can manipulate it find from the command line, but when connecting from node i run into a few problems. Mainly, its that It still says waiting for connections on Port 27017 but the connection is never made, the db I define in mongoose is never created, but also, I don't get any errors.
I do get some deprecation warnings regarding both body-parser and URL string parser. Not sure what to do about that. But also, i'm trying to log either a connection confirmation or an error if it can't connect. Instead it just logs a monster mongoose(?) object. See below
body-parser deprecated bodyParser: use individual json/urlencoded middlewares server.js:15:9 body-parser deprecated undefined extended: provide extended option node_modules\body-parser\index.js:105:29 (node:12152) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. connected to [object Promise] + NativeConnection { base: Mongoose { connections: [ [Circular] ], models: { users: [Function] }, modelSchemas: { users: [Schema] }, options: { pluralization: true }, _pluralize: [Function: pluralize], Schema: { [Function: Schema] reserved: [Object], Types: [Object], ObjectId: [Function] }, model: [Function], plugins: [ [Array], [Array], [Array], [Array] ] }, collections: { users: NativeCollection { collection: [Collection], opts: [Object], name: 'users', collectionName: 'users', conn: [Circular], queue: [], buffer: false, emitter: [EventEmitter] } }, models: { users: { [Function: model] hooks: [Kareem], base: [Mongoose], modelName: 'users', model: [Function: model], db: [Circular], discriminators: undefined, events: [EventEmitter], '$appliedMethods': true, '$appliedHooks': true, _middleware: [Kareem], schema: [Schema], collection: [NativeCollection], Query: [Function], '$__insertMany': [Function], '$init': [Promise], '$caught': true, [Symbol(mongoose#Model)]: true } }, config: { autoIndex: true }, 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: 1, _closeCalled: false, _hasOpened: true, '$internalEmitter': EventEmitter { _events: [Object: null prototype] { dropDatabase: [Function] }, _eventsCount: 1, _maxListeners: 0 }, _listening: false, _connectionOptions: { promiseLibrary: [Function: Promise], useNewUrlParser: false }, name: 'financeDB', host: 'localhost', port: 27017, user: undefined, pass: undefined, client: MongoClient { _events: [Object: null prototype] { left: [Function] }, _eventsCount: 1, _maxListeners: undefined, s: { url: 'mongodb://localhost:27017/financeDB', options: [Object], promiseLibrary: [Function: Promise], dbCache: [Object], sessions: [] }, topology: Server { _events: [Object], _eventsCount: 26, _maxListeners: Infinity, clientInfo: [Object], s: [Object] } }, '$initialConnection': Promise { <pending> }, db: Db { _events: [Object: null prototype] { reconnect: [Function], close: [Function], timeout: [Function] }, _eventsCount: 3, _maxListeners: undefined, s: { databaseName: 'financeDB', dbCache: {}, children: [], topology: [Server], options: [Object], logger: [Logger], bson: BSON {}, readPreference: [ReadPreference], bufferMaxEntries: -1, parentDb: null, pkFactory: undefined, nativeParser: undefined, promiseLibrary: [Function: Promise], noListener: false, readConcern: undefined }, serverConfig: [Getter], bufferMaxEntries: [Getter], databaseName: [Getter] } }
So why is this printing and what am I doing wrong re connection? Here is my server.js:
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose');
config = require('.DB');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true}).then(
()=> {console.log('Database is connected')},
err=>{console.log('Can not connect to the database' + err)}
);
const app = express();
let port = process.env.PORT || 4000;
const server = app.listen(function(){
console.log('Listening on port ' + port);
});
and my DB.js is just the uri
module.exports = {
DB: 'mongodb://localhost:27017/ng7crud'
};

Related

MongoClient - Works on one machine but not the other. How to Output Configuration/Version Information

So I have two machines running in the cloud (both Ubuntu 18.04/Node 13/NPM 6.4) and on one machine I am running into issues with Mongo - I cannot figure out why.
Here is my simple script:
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, async (err, client) => {
if(err) throw err;
console.log('Mongo Client: ', client)
const db = client.db('mydb');
console.log('Mongo DB Connected', db)
const userCount = await db.collection('users').countDocuments()
console.log('# of Users: ', userCount)
});
This works as expected on one machine, but on the other I get the following error:
(node:22716) UnhandledPromiseRejectionWarning: TypeError: db.collection(...).countDocuments is not a function
I am hoping there is a way to have MongoClient spit out it's configuration/version information in the script so that I can see some difference between the two??
Right now when the script runs and I log out "client" I see this on the working machine:
Mongo Client: MongoClient {
_events: [Object: null prototype] { newListener: [Function (anonymous)] },
_eventsCount: 1,
_maxListeners: undefined,
s: {
url: 'mongodb://localhost:27017/mydb',
options: {
servers: [Array],
caseTranslate: true,
useNewUrlParser: true,
useUnifiedTopology: true,
checkServerIdentity: true,
sslValidate: true,
dbName: 'mydb',
socketTimeoutMS: 0,
connectTimeoutMS: 10000,
retryWrites: true,
useRecoveryToken: true,
readPreference: [ReadPreference],
promiseLibrary: [Function: Promise]
},
promiseLibrary: [Function: Promise],
dbCache: Map {},
sessions: Set {},
writeConcern: undefined,
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined
},
namespace: MongoDBNamespace { db: 'admin', collection: undefined }
},
topology: NativeTopology {
...
This is different than what I see on the non-working machine:
Mongo Client: Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: {
databaseName: 'mydb',
dbCache: {},
children: [],
topology: Server {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
s: [Object],
bson: [Getter],
isMasterDoc: [Getter],
poolSize: [Getter],
autoReconnect: [Getter],
host: [Getter],
port: [Getter],
emitOpen: false,
connectTimeoutMS: 30000,
socketTimeoutMS: 0
},
options: {
read_preference_tags: null,
readPreference: [ReadPreference],
url: 'mongodb://localhost:27017/mydb',
promiseLibrary: [Function: Promise],
native_parser: true
},
logger: Logger { className: 'Db' },
bson: BSON {},
authSource: undefined,
readPreference: ReadPreference {
_type: 'ReadPreference',
mode: 'primary',
tags: undefined
},
...
Any guidance would be greatly appreciated.
When all else fails, reboot it. In my case I deleted Mongo and re-installed on the machine not working and now it works.

How to get values from a mongodb cursor from a collection with elements

I'm trying to build a live chart out of a simple mongo colection, using Raspberry Pi 2 with dietPi (DietPi v6.22.3), mongodb and nodejs.
What I'm trying to do is to get data from the db using something like:
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/DB_A';
var str = "";
app.route('/PAGE_A').get(function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
console.log("Connected to db");
var cursor = db.collection('COL_A').find();
console.log(cursor);
//noinspection JSDeprecatedSymbols
cursor.each(function (err, item) {
if (item != null) {
str = str + " DateTime " + item.dt + " - Users: " + item.users + " </br>";
}
});
res.send(str);
db.close();
}
});
});
var server = app.listen(8080, function () {});
Running node app.js and accessing the designated IP:8080/page_A I get the "Connected to db" message but no expected data from the cursor is being printed, except for its parameters I used for this question.
The collection is not empty. I can use DB_A and get elements from db.COL_A.find()...
This is what I get printed in the console when I "npm start" and access IP/PAGE_A:
Connected to db
Cursor {
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
databaseName: 'DB_A',
serverConfig:
Server {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_callBackStore: [CallbackStore],
host: 'localhost',
port: 27017,
options: [Object],
internalMaster: true,
connected: true,
poolSize: 5,
disableDriverBSONSizeCheck: false,
slaveOk: undefined,
_used: true,
replicasetInstance: null,
ssl: false,
sslValidate: false,
sslCA: null,
sslCert: undefined,
sslKey: undefined,
sslPass: undefined,
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
db: [Circular],
dbInstances: [Array],
connectionPool: [EventEmitter],
isMasterDoc: [Object] },
options:
{ read_preference_tags: null,
read_preference: 'primary',
native_parser: false,
readPreference: [ReadPreference],
safe: false,
w: 1 },
_applicationClosed: false,
native_parser: false,
bsonLib:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson: BSON {},
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Function],
DBRef: [Function: DBRef],
Binary: [Function],
ObjectID: [Function],
Long: [Function],
Timestamp: [Function],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey] },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
logger:
{ error: [Function: error],
log: [Function: log],
debug: [Function: debug] },
slaveOk: false,
tag: 1554299599878,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference:
ReadPreference { _type: 'ReadPreference', mode: 'primary', tags: undefined } },
collection:
Collection {
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
databaseName: 'DB_A',
serverConfig: [Server],
options: [Object],
_applicationClosed: false,
native_parser: false,
bsonLib: [Object],
bson: BSON {},
bson_deserializer: [Object],
bson_serializer: [Object],
_state: 'connected',
pkFactory: [Function],
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
auths: [],
openCalled: true,
commands: [],
logger: [Object],
slaveOk: false,
tag: 1554299599878,
eventHandlers: [Object],
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: [ReadPreference] },
collectionName: 'COL_A',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 0,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] } },
selector: {},
fields: undefined,
skipValue: 0,
limitValue: 0,
sortValue: undefined,
hint: null,
explainValue: undefined,
snapshot: undefined,
timeout: true,
tailable: undefined,
awaitdata: undefined,
numberOfRetries: 5,
currentNumberOfRetries: 5,
batchSizeValue: 0,
slaveOk: false,
raw: false,
read: 'primary',
returnKey: undefined,
maxScan: undefined,
min: undefined,
max: undefined,
showDiskLoc: undefined,
comment: undefined,
tailableRetryInterval: 100,
exhaust: false,
partial: false,
totalNumberOfRecords: 0,
items: [],
cursorId: Long { _bsontype: 'Long', low_: 0, high_: 0 },
dbName: undefined,
state: 0,
queryRun: false,
getMoreTimer: false,
collectionName: 'DB_A.COL_A' }
Here are some details on my setup:
mongod --version
db version v2.4.14
node --version
v10.15.3
NodeJS mongo driver -> 1.2.13
cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
cat /etc/debian_version
9.8
uname -a
Linux DietPi 4.14.98+ #1200 Tue Feb 12 20:11:02 GMT 2019 armv6l GNU/Linux
cat /proc/cpuinfo
processor : 0
model name : ARMv6-compatible processor rev 7 (v6l)
BogoMIPS : 697.95
Features : half thumb fastmult vfp edsp java tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xb76
CPU revision : 7
Hardware : BCM2835
Revision : 000e
Serial : 00000000ce0ee037
Thank you.
if you want desire result you can get it using async await
MongoClient.connect(url, async (err, db) => {
if (err) {
console.log(err);
} else {
console.log("Connected to db");
var cursor = await db.collection("comments").find().toArray();
console.log({ cursor });
db.close();
}
});
But if you want to use cursor type with each method of cursor not sure why not working
also change mongodb version "^3.2.2" to "^2.2.33" no luck

TypeError: Cannot read property 'username' of undefined at updateUserList (<MY_PATH>\chatapp\socket\socket.js:34:29)

I am not able to get username & userPic all connected room users.
please suggest me how can I fix it ? please help ~
<MY_PATH>\chatapp\socket\socket.js:34
user:getUsers[i].username,
^
TypeError: Cannot read property 'username' of undefined
at updateUserList (<MY_PATH>\chatapp\socket\socket.js:34:29)
at Socket.<anonymous> (<MY_PATH>\chatapp\socket\socket.js:22:7)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at <MY_PATH>\chatapp\node_modules\socket.io\lib\socket.js:514:12
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
This is the code.
function updateUserList(room, updateALL){
var getUsers = io.of('/messages').in(room).clients();
var userlist = [];
for(var i in getUsers){
userlist.push({
user:getUsers[i].username,
userPic:getUsers[i].userPic
});
}
socket.to(room).emit('updateUsersList', JSON.stringify(userlist));
if(updateALL) {
socket.broadcast.to(room).emit('updateUsersList')
}
}
I am getting data in getUsers as following:
Namespace {
name: '/messages',
server:
Server {
nsps: { '/': [Object], '/roomlist': [Object], '/messages': [Object] },
_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:
Namespace {
name: '/',
server: [Object],
sockets: [Object],
connected: [Object],
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter: [Object] },
eio:
Server {
clients: [Object],
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 60000,
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: [Object],
_events: [Object],
_eventsCount: 1 },
httpServer:
Server {
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_connections: 3,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3000',
[Symbol(asyncId)]: 13 },
engine:
Server {
clients: [Object],
clientsCount: 1,
wsEngine: 'ws',
pingTimeout: 60000,
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: [Object],
_events: [Object],
_eventsCount: 1 } },
sockets:
{ '/messages#g3ylC0osj4SFJlkSAAAC':
Socket {
nsp: [Object],
server: [Object],
adapter: [Object],
id: '/messages#g3ylC0osj4SFJlkSAAAC',
client: [Object],
conn: [Object],
rooms: [Object],
acks: {},
connected: true,
disconnected: false,
handshake: [Object],
fns: [],
flags: {},
_rooms: [],
_events: [Object],
_eventsCount: 3,
username: 'Virendra Kumar',
userPic: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/21078271_1452824561450709_6824442799108958435_n.jpg?oh=38e9461d2dde855c01e085b5ae2f9681&oe=5A7C1B0F' } },
connected:
{ '/messages#g3ylC0osj4SFJlkSAAAC':
Socket {
nsp: [Object],
server: [Object],
adapter: [Object],
id: '/messages#g3ylC0osj4SFJlkSAAAC',
client: [Object],
conn: [Object],
rooms: [Object],
acks: {},
connected: true,
disconnected: false,
handshake: [Object],
fns: [],
flags: {},
_rooms: [],
_events: [Object],
_eventsCount: 3,
username: 'Virendra Kumar',
userPic: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/2799108958435_n.jpg?oh=38e9461d2dde855c01e085b5ae2f9681&oe=5A7C1B0F' } },
fns: [],
ids: 0,
rooms: [],
flags: {},
adapter:
Adapter {
nsp: [Circular],
rooms: { '8229': [Object], '/messages#g3ylC0osj4SFJlkSAAAC': [Object] },
sids: { '/messages#g3ylC0osj4SFJlkSAAAC': [Object] },
encoder: Encoder {} },
_events: { connection: [Function] },
_eventsCount: 1 }
Here is server.js code:
module.exports = function(io, rooms){
// Establish the connection
var chatrooms = io.of('/roomlist').on('connection', function(socket){
console.log('Connection Establish on the server!');
socket.emit('roomupdate', JSON.stringify(rooms)); // sends it back to the user that created it in the first place.
// Receive the new room event.
socket.on('newroom', function(data){
rooms.push(data); // append the data into the array.
socket.broadcast.emit('roomupdate', JSON.stringify(rooms)); // doesn't broadcast to the person that created the room.
socket.emit('roomupdate', JSON.stringify(rooms)); // sends it back to the user that created it in the first place.
})
});
var messages = io.of('/messages').on('connection', function(socket){
console.log('Connected to the Chatroom!');
socket.on('joinroom', function(data){
socket.username = data.user;
socket.userPic = data.userPic;
socket.join(data.room); //push user into partitioned room.
updateUserList(data.room, true);
});
socket.on('newMessage', function(data){
socket.broadcast.to(data.room_number).emit('messagefeed', JSON.stringify(data));
});
function updateUserList(room, updateALL){
var getUsers = io.of('/messages').in(room).clients();
//console.log(getUsers);return false;
var userlist = [];
for(var i in getUsers){
userlist.push({
user:getUsers[i].username,
userPic:getUsers[i].userPic
});
}
socket.to(room).emit('updateUsersList', JSON.stringify(userlist));
if(updateALL) {
socket.broadcast.to(room).emit('updateUsersList')
}
}
socket.on('updateList', function(data){
updateUserList(data.room);
})
});
}

Deploying Node-expressjs app in lambda - [Error: socket hang up] code: ECONNRESET

I am trying to deploy my Expressjs application into lambda, but i am getting below error. Please try to me to resolve this error.
lambda response:
{
"statusCode": 502,
"body": "",
"headers": {}
}
lambda log (it contains console of mongo connection and error)
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
plugins: [],
models: { Student: [Object] },
modelSchemas: { Student: [Object] },
options: { pluralization: true } },
collections:
{ student:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'student',
collectionName: 'student',
conn: [Circular],
queue: [],
buffer: false,
emitter: [Object] } },
models:
{ Student:
{ [Function: model]
hooks: [Object],
base: [Object],
modelName: 'Student',
model: [Function: model],
db: [Circular],
discriminators: undefined,
schema: [Object],
collection: [Object],
Query: [Object],
'$__insertMany': [Function],
insertMany: [Function] } },
config: { autoIndex: true },
replica: false,
hosts: null,
host: '1.0.0.0.0',
port: 3000,
user: undefined,
pass: undefined,
name: 'sudentdb',
options:
{ mongos: {},
db: { safe: true, forceServerObjectId: false },
auth: {},
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} } },
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db:
EventEmitter {
domain: null,
_events:
{ close: [Function],
error: [Function],
reconnect: [Function],
timeout: [Function],
open: [Function],
parseError: [Function] },
_eventsCount: 6,
_maxListeners: undefined,
s:
{ databaseName: 'studentdb',
dbCache: {},
children: [],
topology: [Object],
options: [Object],
logger: [Object],
bson: {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
_events:
{ connected: [Function],
error: [Function],
disconnected: [Function] },
_eventsCount: 3 }
{ [Error: socket hang up] code: 'ECONNRESET' }
student.model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var studentSchema = new Schema({
name: String,
rollnumber: Number,
},{collection:"student"});
module.exports = mongoose.model('Student', studentSchema);
api/student(REST API - GET method)
exports.index = function(req, res) {
console.log(mongoose.connection)
Student.findOne({},function(err,doc){
if(err){
return res.json("error found");
}else{
return res.json(doc);
}
});
};
lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./bin/www');
const server = awsServerlessExpress.createServer(app);
exports.handler = (event,context)=>{
console.log("EVENT: " + JSON.stringify(event));
awsServerlessExpress.proxy(server,event,context);
}

Error when using MongoStore with Express

I'm trying to store the sessions of my Express app in a MongoStore but I get an error at the connection. The error is a huge Object/JSON that I couldn't make sense of, so I tried every alternatives I found online but no luck so far...
Here is the app configuration:
var express = require('express'),
MongoStore = require('connect-mongo')(express),
passport = require('passport');
var app = express();
app.configure(function(){
app.use(express.compress());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8000);
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('secret'));
app.use(express.session({
secret: 'secret',
store: new MongoStore({
db: dbOptions.db,
host: dbOptions.host,
port: dbOptions.port,
username: dbOptions.username,
password: dbOptions.password
},
function(err){
console.log(err || 'connect-mongodb setup ok');
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
And this is the error that is being logged in the console:
{ db:
{ domain: null,
_events: {},
_maxListeners: 10,
databaseName: 'dbname',
serverConfig:
{ domain: null,
_events: {},
_maxListeners: 10,
_callBackStore: [Object],
_commandsStore: [Object],
auth: [Object],
_dbStore: [Object],
host: 'ec2-xx-xxx-xxx-xx.eu-west-1.compute.amazonaws.com',
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: 'ec2-xx-xx-xxx-xx.eu-west-1.compute.amazonaws.com:27017',
_readPreference: null,
socketOptions: [Object],
logger: [Object],
eventHandlers: [Object],
_serverState: 'connected',
_state: [Object],
recordQueryStats: false,
socketTimeoutMS: [Getter/Setter],
db: [Circular],
dbInstances: [Object],
connectionPool: [Object],
isMasterDoc: [Object] },
options: { w: 1 },
_applicationClosed: false,
slaveOk: false,
bufferMaxEntries: -1,
native_parser: undefined,
bsonLib:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
bson: { promoteLongs: true },
bson_deserializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
bson_serializer:
{ Code: [Function: Code],
Symbol: [Function: Symbol],
BSON: [Object],
DBRef: [Function: DBRef],
Binary: [Object],
ObjectID: [Object],
Long: [Object],
Timestamp: [Object],
Double: [Function: Double],
MinKey: [Function: MinKey],
MaxKey: [Function: MaxKey],
promoteLongs: true },
_state: 'connected',
pkFactory:
{ [Function: ObjectID]
index: 16051204,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
forceServerObjectId: false,
safe: false,
notReplied: {},
isInitializing: true,
openCalled: true,
commands: [],
logger: { error: [Function], log: [Function], debug: [Function] },
tag: 1387402758191,
eventHandlers:
{ error: [],
parseError: [],
poolReady: [],
message: [],
close: [] },
serializeFunctions: false,
raw: false,
recordQueryStats: false,
retryMiliSeconds: 1000,
numberOfRetries: 60,
readPreference: undefined },
collectionName: 'sessions',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
readPreference: 'primary',
pkFactory:
{ [Function: ObjectID]
index: 16051204,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString] },
serverCapabilities: undefined }
It's pretty obscure so I have no idea in which direction I should search.
EDIT 1:
Ok thanks that makes more sense now but the thing is I tried to log an error because the sessions aren't stored in MongoDB and I don't understand why. I added a try catch block around the setup of the MongoStore to see if an error was triggered and there is none so I have no clue why it's not working...
This is how passportjs store and retrieve sessions:
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(_id, done) {
var userProvider = new UserProvider();
userProvider.findUser({ _id: _id }, function (err, users) {
if(users.length > 0) { done(null, users[0]); }
else { done(err, null); }
});
});
What am I missing?
Thanks for your help!
Your problem is in the following line:
store: new MongoStore({
db: dbOptions.db,
host: dbOptions.host,
port: dbOptions.port,
username: dbOptions.username,
password: dbOptions.password
},
function(err){
console.log(err || 'connect-mongodb setup ok');
})
Simply remove the last function and I believe it should work as you initially expected
Contrary to Andrei's answer there, the MongoStore constructor does accept a callback. However it's not for error handling purposes - it actually passes back the collection property of MongoStore (which is why console.log spewed out what it did). If there's an error, MongoStore will simply throw an error. You can find it in the source code by clicking here. The callback is invoked on line 164.

Resources