简体   繁体   English

我正在尝试从Express应用程序连接到MongoDB。 我认为我的连接字符串抛出语法错误

[英]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. 嗨,我目前正在使用Express4和MongoDB与猫鼬一起构建和应用程序。 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. 我在Database.js中存储数据库的连接字符串。

Below is the code contained in database.js 以下是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: 这也是我的app.js文件,它使用的是database.js,数据库代码位于第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. 您似乎甚至都没有连接到mongo。 In order to connect to mongo using mongoose you have to use 为了使用猫鼬连接到mongo,您必须使用

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

Also, your database.js is not valid javascript. 另外,您的database.js也不是有效的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). 通常,您可以在本地或通过诸如MongoLab( https://mongolab.com/ )之类的提供程序(免费且可快速开发)运行MongoDB。

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. 然后,为了与您的MongoDB实例进行交互,通常使用Mongoose( http://mongoosejs.com/ ),它是一个对象数据建模器,具有许多有用的功能,可对MongoDB实例执行基本的CRUD操作和许多其他操作。

The code sample is using Mongoose ODM to connect to a MongoLab instance. 该代码示例使用Mongoose ODM连接到MongoLab实例。 The connection string is available from the MongoLab interface. 连接字符串可从MongoLab界面获得。

The Options object is documented here: http://mongoosejs.com/docs/connections.html 选项对象记录在这里: 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. 此外,尽管该示例使用了硬编码的连接字符串,但您可能仍想实现一个certificate.js文件并将其添加到.gitignore文件中,以便您的用户名和密码不会位于代码存储库中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试从 mongodb 连接我的 server.js express api 但它显示一些错误我不明白 - I am trying to connect my server.js express api from mongodb but it showing some error i don't understand it 我正在尝试连接实时服务器。 在iOS中获取连接拒绝错误 - I am trying to connect with my live server. getting Connection refused error in iOS 我应该在连接字符串中输入什么来将我的 NodeJS 应用程序连接到 MongoDB 服务器? - What should I enter to the connection string to connect my NodeJS application to a MongoDB server? 我正在尝试从 heroku 连接到在线 redis 服务器,但我的连接被拒绝 - I am trying to connect to an online redis server from heroku but my connection is getting refused 我的快速应用程序无法连接到mongodb - My express application could not connect to mongodb 运行我的 server.js 尝试连接到我的 sql db 时出现此语法错误 - I get this syntax error when running my server.js trying to connect to my sql db 我正在尝试将 mongodb 服务器与节点连接 - I am trying to connect mongodb server with node 我正在尝试将 Angular 连接到 MongoDB - I am trying to connect Angular to MongoDB 我无法将我的 MongoDb 与 Vs 代码连接起来 - I am unable to connect my MongoDb with Vs code 如何使用 docker-compose 使用此 mongoDB 连接字符串将我的 mongo 数据库连接到我的节点应用程序? - How do I connect my mongo database to my node app with this mongoDB connection string using docker-compose?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM