Node.js connect-mongo database connection problem - mongodb

This is a very weird problem with "connect-mongo"
In my server, I have two scripts.
1) create the express server with session with Mongo DataStore: It has no problem for connection or creating the session.
MongoStore = require('connect-mongo'),
app = require('express').createServer(
express.session({ secret: cfg.wiki_session_secret,
store:new MongoStore({
db: 'mydatabase',
host: '10.10.10.10',
port: 27017
})
})
);
2) just create the store without express:
var MongoStore = require('connect-mongo');
var options = {db: 'mydatabase'};
var store = new MongoStore(options, function() {
var db = new mongo.Db(options.db, new mongo.Server('10.10.10.10', 27017, {}));
db.open(function(err) {
db.collection('sessions', function(err, collection) {
callback(store, db, collection);
});
});
});
That will throw the connection problem:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Error connecting to database
at /home/eauser/node_modules/connect-mongo/lib/connect-mongo.js:106:13
at /home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:79:30
at [object Object].<anonymous> (/home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connections/server.js:113:12)
at [object Object].emit (events.js:64:17)
at Array.<anonymous> (/home/eauser/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection.js:166:14)
at EventEmitter._tickCallback (node.js:126:26)
I just don't know why..

connect-mongo is a middleware for the connect framework, which express is based on.
So, you must use the middleware with the express framework or the connect framework, otherwise it won't work. It's not written to be a standalone session library.

You can go for mongoose to connect. Install using npm command
npm install mongoose
Install mongoose globally
npm install -g mongoose
app.js
var mongoose = require("mongoose");

This module has callback in the constructor which is called when the database is connected, and the collection is initialized so it won't work as you expect.
I've the same problem than you and I wanted the same interface that you aim here. So I wrote another module called YAMS - Yet Another Mongo Store. This is an example with YAMS:
var MongoClient = require("mongodb").MongoClient;
var Yams = require('yams');
var store = new Yams(function (done) {
//this will be called once, you must return the collection sessions.
MongoClient.connect('mongo://localhost/myapp', function (err, db) {
if (err) return done(err);
var sessionsCollection = db.collection('sessions')
//use TTL in mongodb, the document will be automatically expired when the session ends.
sessionsCollection.ensureIndex({expires:1}, {expireAfterSeconds: 0}, function(){});
done(null, sessionsCollection);
});
});
app.usage(express.session({
secret: 'black whisky boycott tango 2013',
store: store
}));
This is in my opinion more flexible than the connect-mongo middleware.

Related

mongodb connection db is undefined with mongoose

I am connecting using Mongoose using the following way
import { createConnection } from 'mongoose';
this.m_context = createConnection('mongodb://localhost/master')
But when I try to access this.m_context.db it is giving me undefined.
What am I doing wrong here? I checked the connection string that is working fine in the compass.
What I found is, createConnection doesn't open connection and because of that, it was giving undefined, as it gives connection DB info only if the connection is open.
this.m_context = await new Promise<Connection>((resolve) => {
createConnection('mongodb://localhost/master', undefined, (error, result) => {
resolve(result)
});
});

Cannot get value of req.user for Passport.js

I spent hours figuring things out why I cannot get the value of req.user when Passport.js serialized a user. But magically, when I deleted the database collection that holds the session, it worked again.
My stack:
Vue.js
Express
Mongoose MongoDb (I store my data on Atlas)
Node.js
I use express-session and connect-mongo to create and save session data and use it to serialize and deserialize user using Passport.js
App.js:
const session = require("express-session");
const passport = require("passport");
const MongoStore = require("connect-mongo")(session);
// Sessions
app.use(
session({
secret: "this is a sample secret",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
//Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
Then I call req.user on a route like this:
router.get("/users", async (req, res) => {
try {
if (req.user) {
res.send(req.user)
} else {
res.send("no-user-found",)
}
} catch (err) {
console.error(err);
}
});
I'm calling /api/users on the front-end with Vue.js and Axios hosted on localhost port 8080. Also, tested on the server itself by calling http://localhost:3000/api/users
Now it works, now that I have deleted the sessions database collection on MongoDb Atlas.
I'm just wondering why this happens? Will it repeat again in the future?

Connected to MLab, but won't connect to localhost

I had this working fine on both localhost and MLab, but then had to switch databases. After much trying I got the database up on MLab, but now it's not connecting to my localhost. Here is my server.js file:
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const mongoose = require("mongoose");
const routes = require("./routes");
// Connect to the Mongo DB
mongoose.connect(process.env.MONGODB_URI || 'mongodb://XXUSERXX:XXPASSWORDXX#ds217388-a0.mlab.com:17388,ds217388-a1.mlab.com:17388/<dbname>?replicaSet=rs-ds217388', { useNewUrlParser: true });
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Add routes, both API and view
app.use(routes);
// Define API routes here
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});
The only line of code I changed was this one below, this is what it was previously:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/wineDB', { useNewUrlParser: true });
I have this app connected in Heroku and had MONGODB_URI defined in the Config Vars, but it wasn't working with the second database until I manually put the connection string in my server.js file. It worked fine with the first one, I don't understand why!
How do I get it to connect to find localhost when it's not running off of MLAB so I can test? Thanks for the help.
It looks like the confusion is from a few different combinations of whether the environment variable being defined or not, as well as whether or not your app is using the variable, instead of falling back to what is defined.
The MONGODB_URI environment variable should contain the connection string for your mLab database and be defined in your Heroku environment both locally and when deployed. I'm assuming that the variable process.env.LOCAL will only be present on your local environment, in situations where your app should be connecting to the local database.
In these cases, something like the following should work:
if(process.env.LOCAL || process.env.MONGODB_URI) {
mongoose.connect(process.env.LOCAL || process.env.MONGODB_URI, { useNewUrlParser: true });
...
} else {
console.log("MongoDB connection string not defined!");
}
We place process.env.LOCAL first, followed the by ||, to say that it gets preference when connecting. Mongoose should then connect to whatever is defined in process.env.LOCAL if present (i.e. your local MongoDB database), falling back to process.env.MONGODB_URI (i.e. mLab) otherwise.
Lastly, it's wrapped in a simple if-else to print out an error message if both values are not defined.

insert data to external mongodb with meteor app

I have an instant of mongodb in the server , ana i connect my meteor app to this DB using that code : lib/connection.js
MONGO_URL = 'mongodb://xxxxxxxx';
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect(MONGO_URL, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to cc', MONGO_URL);
var collection = db.collection('test');
var test1= {'hello':'test1'};
collection.insert(test1);
db.close();
}
});
the connextion to the the external mongo is established and the collection test is created in the server but my app still connected to the the local mongo when i insert my collection: books:
thee code : collections/Books.js
Books= new Mongo.Collection('books');
BooksSchema= new SimpleSchema({
name: {
type: String,
label: "Name"
autoform:{
label: false,
placeholder: "schemaLabel"
}
},
categorie:{
type: String,
label: "Categorie"
autoform:{
label: false,
placeholder: "schemaLabel"
}
},
});
Meteor.methods({
deleteBook: function(id) {
Cultures.remove(id);
}
});
Books.attachSchema(BooksSchema);
code client/books.html
<template name="books">
<p>add new books </p>
{{> quickForm collection="Books" id="newBook" type="insert" class="nform" buttonContent='ajouter' buttonClasses='btn bg-orange'}}
</template>
help bleaaaaaz
You should specify the database that is supposed to be used in MONGO_URL environment variable, not in your code. If you work locally start your application like this:
MONGO_URL="mongodb://xxxxxxxx" meteor
UPD
Don't know about Windows. See this SO question.
Looks like you should set env vars in windows like this:
set MONGO_URL=mongodb://localhost:27017/mydbname
ok thnk you Ramil , i create a new system environment variable on windows , MOGO_URL with value equal : mongodb://xxxxxxxx, and it works; the application is connected to the database in the server , and the data is inserted into it .
now my problem is how to get the data from that DB , I user Microsoft azure to stock the db with API DocumentDB

MongoJS, Node, MongoLab - How to get the database online

I have created an hybrid application with Ionic, MongoJS, Angular JS (Mean Stack).
My application worked fine, locally. This means my mongod (Mongo Service) and my mongo ran locally on my pc. I also have a server.js (node) which is located locally.
Now I would like to use MongoLab (MongoDB as a Service) to change the location of my database from local to online.
I intented to change just the connection path, but for some reason I receive an undefined through my http get request.
My code:
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
//var db = mongojs('nzbaienfurtdb', ['nzbaienfurtdb']); // This is my old mongojs which ran locally and worked fine.
var databaseUrl = 'mongodb://dbuser:password#ds045604.mongolab.com:45604/nzbaienfurtdb';
var db = mongojs(databaseUrl, ['nzbaienfurtdb']); // database online with MongoLab
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/www"));
app.use(bodyParser.json());
app.get('/nzbaienfurtdb', function (req, res) {
console.log("I received a GET request")
db.nzbaienfurtdb.find(function (err, docs){
console.log(docs);
res.json(docs);
});
});
app.listen(3000);
console.log("server running on 3000");
This is a part of my get request out of a service:
service.js
return {
getUsers: function(){""
$http.get("/nzbaienfurtdb")
.success(function(data, status, headers, config){
headers("Cache-Control", "no-cache, no-store, must-revalidate");
headers("Pragma", "no-cache");
headers("Expires", 0);
users = angular.fromJson(data);
})
.error(function(data, status, headers, config){
console.log('Data could not be loaded, try again later');
})
return users;
}
MongoLab has been setup already.
My questions:
Why do I get an undefined for my http GET Request?
What happens with my server.js file when I want to deploy the Ionic App on for example an Android Phone? Is the server running on the device?
Since I have changed the var db variable i get also the following error message in my chrome console:
--------- ERROR CODE:
SyntaxError: Unexpected end of input
at Object.parse (native)
at Object.fromJson (http://localhost:3000/lib/ionic/js/ionic.bundle.js:8764:14)
at http://localhost:3000/js/userServices.js:23:27
at http://localhost:3000/lib/ionic/js/ionic.bundle.js:15737:11
at wrappedCallback (http://localhost:3000/lib/ionic/js/ionic.bundle.js:19197:81)
at wrappedCallback (http://localhost:3000/lib/ionic/js/ionic.bundle.js:19197:81)
at http://localhost:3000/lib/ionic/js/ionic.bundle.js:19283:26
at Scope.$eval (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20326:28)
at Scope.$digest (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20138:31)
at Scope.$apply (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20430:24)
I hope somebody can help me out, I am fighting now for ages!
Thank you in advance, guys!
This issue has been resolved after ages!
I had to enable the API on the website of mongolab in my configuration.