从 mongoose 检索 mongoDB 驱动程序数据库 [英] retrieve mongoDB driver db from mongoose

查看:54
本文介绍了从 mongoose 检索 mongoDB 驱动程序数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个提供构造函数的模块,该函数接受一个 mongo db 实例作为其参数.在我的应用程序中,我尝试使用 mongoose 进行测试.由于 mongoose 是基于 mongoDB 驱动程序模块构建的,因此我假设有一种方法可以从 mongoose 模块中检索 db 驱动程序对象.

I am designing a module provides a constructor function that takes in a mongo db instance as its parameter. In my application I am trying to test this using mongoose. Since mongoose was built on mongoDB driver module, I am assuming that there is a way to retrieve the db driver object from the mongoose module.

我有一个失败的功能,但我不确定原因.

I have a function that is failing but I am unsure to the reason why.

更新

下面是我模块中的代码

//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)});
}

需要导入/需要在另一个文件中配置

It needs to be imported/required in another file to configure

//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 的文件

file with connection to 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() 方法中看到的日志.

I now am not seeing a log that I was hoping to see in the then() method.

  1. mongoose.connection.db 是否等同于返回的 db 实例从 MongoClient.connect ?
  2. mongoClient 不支持 promise 吗?
  3. 你能帮我解决问题吗?

<小时>

答案:@Neil Lunn 为我提供了答案.综上所述,mongoose.connection.db 相当于 MongoClient.connect 返回的 db.另外,我有一个错误,因为我在建立连接之前查询了数据库.


Answer: @Neil Lunn has provided me with the answer. To sum up, mongoose.connection.db is equivalent to the db returned from MongoClient.connect. Also, I had an error because I was querying the db before it has established a connection.

推荐答案

MongoClient 和底层节点驱动当然支持 promises.只是您没有通过实际使用的任何方法引用正确的数据库对象".

MongoClient and the underlying node driver certainly supports promises. It will simply be that you are not referencing the correct "database object" by whatever method you are actually using.

作为演示:

const mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

const uri = 'mongodb://localhost/other',    // connect to one database namespace
      options = { useMongoClient: true };

function log(data) {
  console.log(JSON.stringify(data,undefined,2))
}

(async function() {

  try {

    const conn = await mongoose.connect(uri,options);

    const testDb = conn.db.db('test');  // For example,  get "test" as a sibling

    let result = await testDb.collection('test').find().toArray();
    log(result);

  } catch(e) {
    console.error(e);
  } finally {
    mongoose.disconnect();
  }

})();

所以你应该"做的是获取connection" 对象,并引用 db 从那个.您可能需要当前连接的兄弟"db 空间,并且可能需要 admin" 在您的特定情况下获取身份验证"详细信息.

So what you "should" be doing is getting hold of the "connection" object from the connection, and referencing the db from that. It's likely you want the "sibling" db space of the current connection, and probably "admin" in your specific case for grabbing "authentication" details.

但这里我们使用 .db() 方法脱离 Db 对象 以访问命名兄弟".这显然不是一个异步方法,就像.collection() 不是异步的.

But here we employ the .db() method off of the Db Object in order to access a "named sibling". This is notably not an async method, just like .collection() is not async.

从那里开始,只需从核心驱动程序中实现相应对象的其他本地方法即可.

From there it's just a matter of implementing other methods native to the respective object from the core driver.

这篇关于从 mongoose 检索 mongoDB 驱动程序数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆