node.js - 如何使用 URL 连接到 MongoDB 服务器?
问题描述
我不知道在这个脚本中将 MongoDB 中数据库的 URL 放在哪里,例如url : mongodb:localhost/mydb
. 我在介绍和教程中找不到任何答案。
var MongoClient = require('mongodb').MongoClient
var state = {
db: null,
}
exports.connect = function(url, db, done) {
if (state.db) return done();
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, client) {
if (err) return done(err)
state.db = client.db(db);
done();
});
}
exports.get = function() {
return state.db;
}
exports.close = function(done) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null;
state.mode = null;
done(err);
})
}
}
解决方案
您可以在选项参数中设置 DB。
MongoClient.connect(url, { db: '' }, function(err, client) {
...
});
见https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html#connect
推荐阅读
- c - Visual Studio 中的 CMAKE 似乎可以识别头文件,但无论如何都无法构建
- python - 无法将 org 模块导入 PySpark 集群
- powershell - 使用此 powershell 脚本未获得结果
- raku - 将非标量分配给标量有什么好处?
- c++11 - 找到后显示元素的索引
- python - python中具有不同列数的2xN矩阵的hausdorff距离
- reactjs - React Hook 更新不改变子组件的样式
- javascript - 在页面之间切换时保持按钮处于活动状态
- python - 从 python 脚本的另一部分获取对象而不激活整个脚本
- c++ - 使用 OpenGL 对多边形进行透视投影