MongoError:数据库名称不能包含字符' '当使用mongoosejs连接到mLab时

时间:2017-02-27 06:29:50

标签: node.js mongodb mongoose

这是我的JS代码:

var mongoose = require('mongoose'); 

mongoose.connect("mongodb://myUsername:myPassword@ds161039.mlab.com:61039/accounttest");

这是我启动服务器时的错误

C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongodb\lib\db.js:1774
if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true});
                                                ^
MongoError: database names cannot contain the character ' '
at Function.MongoError.create (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongodb-core\lib\error.js:31:11)
at validateDatabaseName (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongodb\lib\db.js:1774:70)
at new Db (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongodb\lib\db.js:154:3)
at NativeConnection.doOpen (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongoose\lib\drivers\node-mongodb-native\connection.js:55:15)
at NativeConnection.Connection._open (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongoose\lib\connection.js:531:15)
at C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongoose\lib\connection.js:289:11
at new Promise.ES6 (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongoose\lib\promise.js:45:3)
at NativeConnection.Connection.open (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongoose\lib\connection.js:288:17)
at Mongoose.connect (C:\Users\Qk Lahpita\Desktop\server_node_2\node_modules\mongoose\lib\index.js:242:47)
at Object.<anonymous> (C:\Users\Qk Lahpita\Desktop\server_node_2\server.js:36:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)

我的数据库的名称是&#34; accounttest&#34;,不包含&#39; &#39;字符。为什么我有这个错误,我该如何解决?

谢谢!

3 个答案:

答案 0 :(得分:1)

问题在于您的数据库名称本身。您不应有空格。

示例

const databaseName = "Users"
const connectionURI = "mongodb://127.0.0.1"

MongoClient.connect(connectionURI,{useUnifiedTopology:true},(err,client) => {
if(err) return log("Unable to connect to database");
log("Database Connected")

const db = client.db(databaseName);

然后您可以按照示例进行操作:

db.addUser("John","kio")

答案 1 :(得分:0)

我假设myUsernamemyPassword不是您真正的价值观。如果您的用户名或密码包含某些特殊字符,则可能需要对其进行编码。如果是这种情况,请尝试以下方法:

mongoClient.connect("mongodb://myEncodedUsername:myEncodedPassword@ds161039.mlab.com:61039/accounttest", {uri_decode_auth: true}, function(err, db) {
});

答案 2 :(得分:0)

1。创建一个database.js文件

在其中进行可导出的数据库配置,如下所示

module.exports = {database : "mongodb://myUsername:myPassword@ds161039.mlab.com:61039/accounttest"};

2。需要它到您当前的JS文件中

var connection = mongoose.connect(config.database);