ala*_*udi 2 mongoose mongodb node.js
我正在设计一个模块,提供一个构造函数,该函数接受一个 mongo db 实例作为其参数。在我的应用程序中,我尝试使用 mongoose 进行测试。由于 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)});
}
Run Code Online (Sandbox Code Playgroud)
需要在另一个文件中导入/需要配置
//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;
Run Code Online (Sandbox Code Playgroud)
与 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
Run Code Online (Sandbox Code Playgroud)
我现在没有看到我希望在then()方法中看到的日志。
答案: @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();
Run Code Online (Sandbox Code Playgroud)
使用连接对象检索 MongoDB 驱动程序实例。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testdb', function (err){
if (err) throw err;
let db = mongoose.connection.db; // <-- This is your MongoDB driver instance.
});
Run Code Online (Sandbox Code Playgroud)
MongoClient 和底层节点驱动程序当然支持 Promise。这只是因为您没有通过实际使用的任何方法引用正确的“数据库对象”。
作为演示:
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();
}
})();
Run Code Online (Sandbox Code Playgroud)
因此,您“应该”做的是从连接中获取“连接”db对象,并从中引用。您可能想要db当前连接的“兄弟”空间,并且可能"admin"在您的特定情况下用于获取“身份验证”详细信息。
但这里我们使用对象.db()的方法来访问“命名的同级”。值得注意的是,这不是一个异步方法,就像不是异步一样。Db.collection()
从那里开始,只需实现核心驱动程序中相应对象的其他本机方法即可。