面试题答案
一键面试配置思路
- 自动加载常用自定义模块:在
.mongorc.js
文件中,可以使用load()
函数来加载自定义的 JavaScript 文件,这些文件包含常用的函数或工具模块。 - 权限检查:利用 MongoDB 的钩子函数,如
db.collection('集合名').find()
、db.collection('集合名').update()
等操作前,调用权限检查函数checkCollectionPermission
进行权限验证。
关键代码示例
- 自动加载自定义模块:
假设我们有一个自定义模块
myUtils.js
,内容如下:
// myUtils.js
function myFunction() {
return "This is my custom function";
}
exports.myFunction = myFunction;
在.mongorc.js
中加载此模块:
load('path/to/myUtils.js');
- 权限检查:
// 假设权限检查函数已经定义
function checkCollectionPermission(collectionName, operation) {
// 这里编写实际的权限检查逻辑,返回 true 或 false
return true;
}
// 对 find 操作进行权限检查
const originalFind = db.collection('特定集合名').find;
db.collection('特定集合名').find = function() {
if (checkCollectionPermission('特定集合名', 'find')) {
return originalFind.apply(this, arguments);
} else {
throw new Error("没有权限执行此操作");
}
};
// 对 update 操作进行权限检查
const originalUpdate = db.collection('特定集合名').update;
db.collection('特定集合名').update = function() {
if (checkCollectionPermission('特定集合名', 'update')) {
return originalUpdate.apply(this, arguments);
} else {
throw new Error("没有权限执行此操作");
}
};