【发布时间】:2019-09-06 12:01:42
【问题描述】:
我正在设计一个模块,它提供了一个构造函数,该函数接受一个 mongo db 实例作为其参数。在我的应用程序中,我正在尝试使用猫鼬对此进行测试。由于 mongoose 是基于 mongoDB 驱动模块构建的,我假设有一种方法可以从 mongoose 模块中检索 db 驱动对象。
我有一个失败的功能,但我不确定原因。
更新
下面是我模块中的代码
//authorizer.js
function Authorizer(mongoDBCon, userOptions){
this.db = mongoDBCon;
this.authorize = authorize;
this.assignOwner = assignOwner;
this.setUserPermission = setUserPermission;
this.setRolePermission = setRolePermission;
this.retrieveUserPermission = retrieveUserPermission;
this.setRolePermission = setRolePermission;
let defaultOptions = {
unauthorizedHandler: (next)=>{
let error = new Error('user has performed an unauthorized action');
error.status = 401;
next(error);
},
userAuthCollection: 'user_authorization',
roleAuthCollection: 'role_authorization',
}
this.options = _.assign({},defaultOptions,userOptions);
}
function setRolePermission(role, resource, permissions) {
let document = {
role: role,
resource: resource,
permissions: permissions,
};
//add the document only if the role permission is not found
let collection = this.db.collection(this.options.roleAuthCollection);
collection.findOne(document)
.then((result)=>console.log('in here')) //------> not printing :(
.catch(e=>{console.log(e)});
}
需要导入/需要在另一个文件中配置
//authorizerConfig
let mongoose = require('mongoose');
let Authorizer = require('util/authorization/authorization');
let authorizer = new Authorizer(mongoose.connection.db);
//set admin role permissions
authorizer.setRolePermission('admin', 'users', '*');
authorizer.setRolePermission('admin', 'postings', '*');
module.exports = authorizer;
连接到 mongo 的文件
//app.js
// Set up and connect to MongoDB:
const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect(process.env.MONGODB_URI);//MONGODB_URI=localhost:27017/house_db
我现在没有看到我希望在 then() 方法中看到的日志。
- mongoose.connection.db 是否等同于返回的 db 实例 来自 MongoClient.connect ?
- mongoClient 不支持承诺吗?
- 您能帮我解决问题吗?
答案: @Neil Lunn 为我提供了答案。综上所述,mongoose.connection.db就相当于MongoClient.connect返回的db。另外,我遇到了一个错误,因为我在建立连接之前查询了数据库。
【问题讨论】:
-
但据我所知,这个构造函数如何知道 this.db 是什么并找到它的功能。发布您的完整代码,您将如何实现它。如果你完全依赖 mongodb 原生模块或者选择 mongoose,它也会很棒。
-
@rxysm 不需要。尼尔伦恩回答了我的问题。他似乎明白了我的问题。