【问题标题】:Is there a way to override default functions in Mongodb?有没有办法覆盖 Mongodb 中的默认函数?
【发布时间】:2014-12-11 15:01:58
【问题描述】:

所以我想做的是让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); 
}

originalFindOne 将链接到默认的findOne,这根本不起作用。因此,在没有运气找到覆盖默认函数的方法之后,我想也许我可以创建一个新函数,如 db.collection.simpleFindOne() 或其他东西,但我找不到将它附加到 mongo shell 以便它可用的方法到任何集合。

有人对 mongo 内部的工作原理有什么见解可以给我一些帮助吗?

【问题讨论】:

    标签: mongodb mongo-shell


    【解决方案1】:

    尝试将此 sn-p 添加到您的 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);
      };
    }
    
    })();
    

    我最初通过在 Mongo shell 中输入 db.myCollection.constructor 找到了 DBCollection 对象/类。然后我通过验证 (a) DBCollection 是全局可访问的,(b) DBCollection.prototype 存在,以及 (c) typeof DBCollection.prototype.findOne === "function" (很像 sn-p )。


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

    【讨论】:

    • 正是我想要的!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多