我正在编写一个 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/