node.js - 将 Mongoose 连接传递给模块

标签 node.js mongodb mongoose

我正在编写一个 Node 模块,它将对 MongoDB 执行查询。

我的模块应该将 MongoDB 连接作为参数(当我使用 new MyModule(db) 初始化它时)并在其中使用它。

我使用的是没有任何 NPM 模块的标准 MongoDB,并且我在我的 db 变量中传递了与 MongoDB 的连接。现在我要切换到 Mongoose,但找不到将 Mongoose 连接传递到我的模块的方法。

我不想在我的模块内初始化 Mongoose 连接,因为我想与我的测试和其他模块共享它。

我该怎么办?我试过将 mongoose 传递给我的模块,但它不起作用“不是函数”。

编辑:

阅读@Neil Lunn 的回复后,我发布了我的模块示例:

(function () {
    "use strict";

    /**
     *  various requires
     */

    function TopicManager(dbURI) {
        if (!(this instanceof TopicManager)) { return new TopicManager(dbURI); }
        mongoose.connect(dbURI);
    }

    TopicManager.prototype.save = function (topics, done) {

        var Topic = new mongoose.schema(
            {
                title: { type: String },
                slug: { type: String, index: { unique: true } }
            },
            {collection : "topics"}
        );

        /**
         * Use monguurl on "slug"
         */

        mongoose.update(
            {title: topic.title},
            {upsert: true},
            function (err, numberAffected, raw) {
                if (err) { return done(err); }
                return done(null, raw);
            }
        );    
    };

    module.exports = TopicManager;
})();

它不起作用,因为当我使用它时,当它运行 new mongoose 时,我得到 undefined is not a function

最佳答案

一般来说,您不会这样做。使用 mongoose 的思维方式与使用原始形式的本地驱动程序略有不同,并且有很多东西可以帮助在引擎盖下使事情更无缝地工作,而无需深入研究血淋淋的细节。

所以基本的方法是当你定义你的“schema”和“models”时,它们被绑定(bind)到默认的连接实例。除非您有特定原因绑定(bind)到另一个连接,否则您应该遵循以下内容:

所以你会有一个架构和模型定义:

var mySchema = new Schema({
    "name": String
});

module.exports = mongoose.model( "Model", mySchema, "collection" )

其中“集合”部分是可选的,否则第一个参数中的“模型”名称将符合标准规则,通常是小写和复数形式。

然后在您的其他代码 list 中,您使用 require:

var Model = require('./models/mymodel.js');

并在 mongoose 允许的情况下使用您的模型对象:

Model.find({ "field": "name"}, function(err,models) {

});

因此它允许比使用基本驱动程序完成的处理更抽象一些,因为“模型”本身知道如何绑定(bind)到连接,或者以其他方式显式绑定(bind)到您想要的连接作为可选参数。

关于node.js - 将 Mongoose 连接传递给模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24474386/

相关文章:

mongodb - 如何运行 mongo-express(无需身份验证)?

node.js - 我应该在 Node.js 中同时使用 MongoDB 和 Mongoose 吗?

mongodb - 如何避免向 MongoDB 中的数组添加重复的对象

javascript - Mongoose JS 关系

node.js - 使用 Node JS 验证 jwt token 和代理到另一台服务器

javascript - 动态单选按钮表单 react

mongodb - Angular 1.2.0 : Error: "Referencing private fields in Angular expressions is disallowed" when attempting to access Mongo _id fields

javascript - Mongoose验证错误: first: Path `first` is required.,最后: Path `last` is required.“

node.js - 使用 Node 和 makefile 使用 LESS 编译 Bootstrap

javascript - NodeJS (ExpressJS) 未处理的拒绝 TypeError : callback is not a function