有没有办法覆盖Mongodb中的默认功能?

Sha*_*ded 5 mongodb mongo-shell

所以我想做的是使findOne工作更像在Meteor中,但要通过Mongo shell。简而言之,我希望能够执行类似的操作db.collection.findOne("thisIsAnId")并在该集合中查找该ID。

我尝试加载包含此文件的文件...

db.collection.findOne = function(query, fields, options){
    if(typeof query === "string") {
        return db.collection.originalFindOne({_id : query}, fields, options);
    }

    return db.collection.originalFindOne(query, fields, options); 
}
Run Code Online (Sandbox Code Playgroud)

originalFindOne仅在哪里链接到default findOne,这根本不起作用。因此,在没有办法找到覆盖默认函数的方法之后,我想也许我可以创建一个新的函数,诸如此类db.collection.simpleFindOne(),但是我找不到一种将其附加到mongo shell的方法,以便任何集合都可以使用它。 。

任何人都对mongo内部工作原理有一些见识,可以给我一些帮助吗?

Jam*_*ene 5

尝试将此代码段添加到您的Mongo配置文件之一:

(function() {

// Duck-punch Mongo's `findOne` to work like Meteor's `findOne`
if (
  typeof DBCollection !== "undefined" && DBCollection &&
  DBCollection.prototype && typeof DBCollection.prototype.findOne === "function" &&
  typeof ObjectId !== "undefined" && ObjectId
) {
  var _findOne = DBCollection.prototype.findOne,
      _slice = Array.prototype.slice;
  DBCollection.prototype.findOne = function() {
    var args = _slice.call(arguments);
    if (args.length > 0 && (typeof args[0] === "string" || args[0] instanceof ObjectId)) {
      args[0] = { _id: args[0] };
    }
    return _findOne.apply(this, args);
  };
}

})();
Run Code Online (Sandbox Code Playgroud)

我最初是DBCollection通过db.myCollection.constructor在Mongo shell中键入来找到对象/类的。然后,我findOne通过验证(a)可以DBCollection全局访问,(b)DBCollection.prototype存在和(c)typeof DBCollection.prototype.findOne === "function"(类似于代码段)来确认其原型上已定义。


编辑:添加了一个逻辑分支以涵盖基于ObjectId的ID。