简体   繁体   中英

Connecting to MongoDB using Mongoose

I'm trying to connect to my MongoDB on mLab using by

var mongoose = require('mongoose');
var User = require('./modules/User');

mongoose.connect('mongodb://<dbuser>:<dbpassword>@ds020168.mlab.com:20168/test_database');

I´ve stored this code in a file called test.js. Now, when I run the command

node test.js 

it outputs the following error message:

SyntaxError: Invalid or unexpected token
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

I haven't set up an Express application, my projects just comprises of this test.js file and a package.json file with the required dependecies added and installed. Additionally, I've created a User model that is also imported into test.js.

Can someone explain to a beginner what else is required to successfully establish a connection and why the above code doesn't suffice? Besides, what does the error message tell me?

Did you change < dbuser> and < dbpassword> to yours?

Correct approach is:

mongoose.connect('mongodb://USERNAME:PASSWORD@ds020168.mlab.com:20168/test_database');

And NOT

mongoose.connect('mongodb://<USERNAME>:<PASSWORD>@ds020168.mlab.com:20168/test_database');

User 模块中可能存在语法错误,并且 node.js 无法导入它。

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