node.js - 如何使 mongoDB 实例可用于 Node.js 中的所有其他模块

标签 node.js mongodb

在我的应用程序中,我将 node.js 与 mongoDB 一起使用。下面是我的示例代码。

var mongodb = require('mongodb');
var server = new mongodb.Server("localhost", 27017, {});

new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
    if (error) throw error;
    var collection = new mongodb.Collection(client, 'test_collection');
    collection.insert({hello: 'world'}, {safe:true},
    function(err, objects) {
        if(!err){
            console.log('Data inserted successfully.');
        }
        if (err && err.message.indexOf('E11000 ') !== -1) {
            // this _id was already inserted in the database
        }
    });
});   

现在我需要应用程序中其他模块的 mongoDB 实例。我该如何执行此操作。

最佳答案

一个简单的方法,如果我们假设您发布的代码位于 app.js 中,您可以将第 2 行重写为:

var server = exports.db = new mongodb.Server("localhost", 27017, {});

在需要访问实例的模块中只需编写:

require('app').db

更常见的方法可能是将共享内容放入 settings.js 文件中或拥有专用的数据库接口(interface)模块。

更新

要访问打开的客户端,您需要以相同的方式公开客户端:

new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
  exports.client = client;
  // ...
});   

关于node.js - 如何使 mongoDB 实例可用于 Node.js 中的所有其他模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470895/

相关文章:

c# - 如何测试 MongoDB 文档中的字符串字段不为空?

javascript - 如何在 express js 中使用 get 方法从 mongo db 中获取数据?

javascript - 我正在尝试在 findAll 中包含许多关联,但出现错误

node.js - 有哪些开源 Node.js CI 项目?

javascript - 使用 jsdom 或 Canvas for node.js 获取 Vibrant.js 样本

javascript - 为什么在访问对象内的数组时出现未定义?

javascript - 能够查询数组中的特定索引吗? Mongoose

javascript - Firebase 模块在部署功能时需要旧版本的 Node

node.js - 使用 nconf 和 env 的只读配置值

jquery - 使用 AJAX 在 nodeJS Express MongoDB 中发送 post 请求