简体   繁体   中英

I am trying to connect to connect to MongoDB from my Express Application. It is throwing a syntax error at my connection string I think

Hi I am currently working on building and application using Express4 and MongoDB with mongoose. When I try to run my application I am receiving this error

    /config/database.js:3
    };
    ^
    SyntaxError: Unexpected token }

Database.js is where I am storing the connection string for my DB.

Below is the code contained in database.js

    module.exports = {
    mongodb://username:password@ds033669.mongolab.com:33669/dclubdb
    };

Here is also my app.js file that is using the database.js the db code is on line 21:

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');

    var mongoose = require('mongoose');
    var flash    = require('connect-flash');
    var passport = require('passport');
    var session      = require('express-session');

    var routes = require('./routes/index');
    var users = require('./routes/users');
    var admins = require('./routes/admin');



    var app = express();

    var configDB = require('./config/database.js');


    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');

    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    //routes
    app.use('/', routes);
    app.use('/users', users);
    app.use('/admin', users);

    //required for passport
    app.use(session({ secret: 'mysecret' })); // session secret
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
    app.use(flash());


    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
          message: err.message,
          error: err
        });
      });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: {}
      });
    });


    //require('./routes/admin.js')(app, passport);


    module.exports = app;

Sorry to bother you and thank you for your time in advance. If there any more information I can include please let me know.

There are two problems with your code as far as I can see:

You seem not to not even connect to mongo. In order to connect to mongo using mongoose you have to use

mongoose.connect('mongodb://...');

Also, your database.js is not valid javascript. It's not the connection string itself that's the problem, but rather that you don't assign in to a variable.

A correct way would be to assign the connection string to a property like this:

module.exports = {
    connString: 'mongodb://username:password@ds033669.mongolab.com:33669/dclubdb'
};

and then you could connect with

mongoose.connect(configDB.connString);
//setup database connection
var options = {
    server: {
        socketOptions: { keepAlive: 1 }
    }
};
mongoose.connect('mongodb://username:password@server.mongolab.com:port/app', options);

To explain (per suggestion). You typically run MongoDB either locally or through a provider like MongoLab ( https://mongolab.com/ ) (which is free and great for quick development).

Then, to interact with your MongoDB instance, you typically use Mongoose ( http://mongoosejs.com/ ), which is an Object Data Modeler with a lot of useful functionality for doing basic CRUD operations and many other things to your MongoDB instance.

The code sample is using Mongoose ODM to connect to a MongoLab instance. The connection string is available from the MongoLab interface.

The Options object is documented here: http://mongoosejs.com/docs/connections.html

Additionally, although the example uses a hard coded connection string, you probably want to implement a credentials.js file and add it to your .gitignore file so your username and password is not sitting in a code repository.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM