连接到 MongoDB 集合的问题
Posted
技术标签:
【中文标题】连接到 MongoDB 集合的问题【英文标题】:Issue Connecting to MongoDB collections 【发布时间】:2019-04-17 19:59:49 【问题描述】:我正在使用 axios 和 express.js API 连接到我的 mongo 数据库。我有一个适用于一个集合的 .get() 请求,不适用于任何其他集合。这当前将连接到数据库并可以访问称为用户的集合之一。我在同一个数据库下有另一个集合设置,称为任务,我的用户和任务设置方式相同,并且在代码中使用方式相同。用户可以连接到数据库(get、post),并且在调用 get 或 post 函数时任务无法连接到集合。在浏览器中查看 .get() API 请求时,它只是挂起,从不返回任何内容或完成请求。
任何帮助将不胜感激!
该项目位于 SCRUM-150 下的 GitHub 上。
API connection
MONGO_URI=mongodb://localhost:27017/mydb
Working
methods:
//load all users from DB, we call this often to make sure the data is up to date
load()
http
.get("users")
.then(response =>
this.users = response.data.users;
)
.catch(e =>
this.errors.push(e);
);
,
//opens delete dialog
setupDelete(user)
this.userToDelete = user;
this.deleteDialog = true;
,
//opens edit dialog
setupEdit(user)
Object.keys(user).forEach(key =>
this.userToEdit[key] = user[key];
);
this.editName = user.name;
this.editDialog = true;
,
//build the alert info for us
//Will emit an alert, followed by a boolean for success, the type of call made, and the name of the
//resource we are working on
alert(success, callName, resource)
console.log('Page Alerting')
this.$emit('alert', success, callName, resource)
this.load()
,
//get those users
mounted()
this.load();
;
Broken
methods:
//load all tasks from DB, we call this often to make sure the data is up to date
load()
http
.get("tasks")
.then(response =>
this.tasks = response.data.tasks
)
.catch(e =>
this.errors.push(e);
);
,
//opens delete dialog
setupDelete(tasks)
this.taskToDelete = tasks;
this.deleteDialog = true;
,
//opens edit dialog
setupEdit(tasks)
Object.keys(tasks).forEach(key =>
this.taskToEdit[key] = tasks[key];
);
this.editName = tasks.name;
this.editDialog = true;
,
//build the alert info for us
//Will emit an alert, followed by a boolean for success, the type of call made, and the name of the
//resource we are working on
alert(success, callName, resource)
console.log('Page Alerting')
this.$emit('alert', success, callName, resource)
this.load()
,
//get those tasks
mounted()
this.load();
;
【问题讨论】:
【参考方案1】:您是否在代码中设置任何访问控制?
另请参阅此处的 mongoDB 文档: https://docs.mongodb.com/manual/core/collection-level-access-control/
【讨论】:
目前没有,一切都对所有用户开放。【参考方案2】:这是我的解决方案: 在你的 app.js 中,有这个:
let mongoose = require('mongoose');
mongoose.connect('Your/Database/Url',
keepAlive : true,
reconnectTries: 2,
useMongoClient: true
);
在你的路线上有这个:
let mongoose = require('mongoose');
let db = mongoose.connection;
fetchAndSendDatabase('yourCollectionName', db);
function fetchAndSendDatabase(dbName, db)
db.collection(dbName).find().toArray(function(err, result)
if( err )
console.log("couldn't get database items. " + err);
else
console.log('Database received successfully');
);
【讨论】:
这会去哪里让它工作?这会放在 routes.js 还是 app.js 文件中?以上是关于连接到 MongoDB 集合的问题的主要内容,如果未能解决你的问题,请参考以下文章
MongoDB 错误:连接到 mongo 副本集时无法到达集合 [set_name] 的主节点
在 express.js 中连接到 Mongodb-Native-Driver
使用 rmongodb 时,在 mongoDB 中看不到集合