我正在设计一个模块,提供一个构造函数,该函数接受 mongo db 实例作为其参数。在我的应用程序中,我尝试使用 Mongoose 来测试这一点。由于 mongoose 是在 mongoDB 驱动程序模块上构建的,因此我假设有一种方法可以从 mongoose 模块检索数据库驱动程序对象。
我有一个函数失败了,但我不确定原因。
更新
下面是我的模块中的代码
//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 是否相当于返回的数据库实例 来自 MongoClient.connect ?
- mongoClient 不支持 Promise 吗?
- 您能帮助解决我的问题吗?
答案: @Neil Lunn 为我提供了答案。综上所述,mongoose.connection.db相当于MongoClient.connect返回的db。另外,我遇到了错误,因为我在数据库建立连接之前查询了数据库。
最佳答案
请注意,这似乎在某些时候发生了变化,在 v5 中我可以像这样访问数据库:
const res = await mongoose.connect(...);
const { db } = mongoose.connection;
const result = await db.collection('test').find().toArray();
关于node.js - 从 mongoose 检索 mongoDB 驱动程序数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272404/