我是MongoDB的新手,我只是在Ubuntu终端中设置MongoDB,mongod和mongo命令在不同的终端中运行。然而,我无法让我的app.js正常运行。这是代码的开头:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var helpers = require('handlebars-helpers')();
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var fs = require('fs');
var net = require('net');
process.on('uncaughtException', (err) => {
console.log(err);
});
//const config = {
// autoIndex: false,
// useNewUrlParser: true
//};
//return mongoose.connect(uri, config);
//Log into MongoDB server
//var db = mongoose.connection;
const db = mongoose.connection
const url = 'mongodb://127.0.0.1:27017/modeltest'
mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log('DB Connection Error: ' + err);
});
当我运行node app.js
时,我得到以下错误:
{ MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at new MongooseError (/home/ubuntu/modeltest/web/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at NativeConnection.Connection.openUri (/home/ubuntu/modeltest/web/node_modules/mongoose/lib/connection.js:579:11)
at Mongoose.connect (/home/ubuntu/modeltest/web/node_modules/mongoose/lib/index.js:333:15)
at Object.<anonymous> (/home/ubuntu/modeltest/web/app.js:31:10)
at Module._compile (module.js:652:30)
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:188:16)
at bootstrap_node.js:609:3
message: 'The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.',
name: 'MongooseError' }
ubuntu@ip-172-31-27-34:~/mod
关于如何修改代码以正常工作,有什么建议吗?
更新:我还试图通过对代码的一些修改来连接到我建立的Mongo Atlas数据库:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var helpers = require('handlebars-helpers')();
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var fs = require('fs');
var net = require('net');
process.on('uncaughtException', (err) => {
console.log(err);
});
//const config = {
// autoIndex: false,
// useNewUrlParser: true
//};
//return mongoose.connect(uri, config);
//Log into MongoDB server
var db = mongoose.connection;
//const db = mongoose.connection
//console.log(process.env.MONGO_URI)
const {MongoClient} = require('mongodb');
async function main(){
const uri = "mongodb+srv://theusernamewhichientered:thepassword@modeltest-3lpoi.mongodb.net/test?retryWrites=true&w=majority"
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
await listDatabases(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client){
databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
但当我运行node app.js
:时,我得到了以下输出
DIRNAME
/home/ubuntu/modeltest/web
Server started on port 3000
{ MongoServerSelectionError: connection <monitor> to 52.203.196.37:27017 closed
at Timeout.waitQueueMember.timer.setTimeout [as _onTimeout] (/home/ubuntu/modeltest/web/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
name: 'MongoServerSelectionError',
reason:
TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers:
Map {
'modeltest-shard-00-00-3lpoi.mongodb.net:27017' => [Object],
'modeltest-shard-00-01-3lpoi.mongodb.net:27017' => [Object],
'modeltest-shard-00-02-3lpoi.mongodb.net:27017' => [Object] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null },
[Symbol(mongoErrorContextSymbol)]: {} }
我能做些什么来克服这一点?
看起来错误是说变量process.env.MONGO_URI
是undefined
。请尝试在mongoose连接之前添加console.log(process.env.MONGO_URI)
,因为可能未设置MONGO_URI变量。或者,尝试传递url
变量,而不是process.env.MONGO_URI