如何在Node Express应用程序中传递对象?

4
我正在使用express和node-postgres(https://github.com/brianc/node-postgres)构建一个基于Node的应用程序。我只想建立一次数据库客户端连接,并且希望能够从不同的模块访问此数据库连接。最好的方法是什么?我试图只导出db连接,而不是整个express应用程序。实质上,如何在Node应用程序中导出和访问对象是最好的方式?
我查看了这个类似的问题,但它似乎只适用于mongoose。 最佳方法与mongoose / node.js共享数据库连接参数
3个回答

5

并不存在所谓的“最佳方式”。如果您需要在不同模块之间使用相同的对象,则必须将其包装在一个模块中。可以像这样实现:

//db.js
var postgres = require (...)
var connection;

module.exports = {
  getConnection: function (){
    return connection;
  },
  createConnection: function (){
    connection = createConnection (postgress);
  }
};

//app.js - main file
require ("./db").createConnection ();

//a.js
var db = require("./db")
db.getConnection()

//b.js
var db = require("./db")
db.getConnection()

0

嗨,我正在解决这个问题,它来自RefLink

您可以创建这样的方案来映射您的数据

    const User = mongoose.model('Story', userSchema);
    module.exports = User;
    const mongoose = require('mongoose');
    let Schema = mongoose.Schema;
    const userSchema = new Schema({
    UserID: {
        type: mongoose.Schema.Types.Mixed,
    },
    User_Info: {
        First_Name: {
        type: String,
        },
        Last_Name: {
        type: String,
        },
        Current_Address: {
        type: String,
        },
        Email_Address: {
        type: String,
        },
    },
        Phone_Numbers: [{
            Home_Phone: {
            type: Number,
            },
            Work_Phone: {
            type: Number,
            },
            Cell_Phone: {
            type: Number,
            },
                Phone_verified: [{
                Home: Boolean,
                Work: Boolean,
                Cell: Boolean,
                }],
        }],
    })
    const User = mongoose.model('User', userSchema);
    module.exports = User;

而 API 路由可能看起来像这样

        app.post('/api/user', function(req, res) {
    User.create({
        UserID: req.body.userid,
        User_Info: req.body.userinfo,
        First_Name: req.body.firstname,
        Last_Name: req.body.lastname,
        Current_Address: req.body.currentaddress,
        Email_Address: req.body.emailaddress,
        Phone_Numbers: req.body.phonenumbers,
        Home_Phone: req.body.homephone,
        Work_Phone: req.body.workphone,
        Cell_Phone: req.body.cellphone,
        Phone_Verified:
        req.body.phoneverified,
        Home: req.body.home,
        Work: req.body.work,
        Cell: req.body.cell,
    }).then(user => {
        res.json(user)
    });
    });

-1

你可以这样做...

//db.js
var pg = require('pg'); 

var conString = "tcp://postgres:1234@localhost/postgres";

module.exports.connectDatabase = function(callback){
var client = new pg.Client(conString);
client.connect(function(err) {
  if(err){
     console.log(err);
     process.exit(1);
  }

  module.exports.client = client;
  callback();
})

//app.js
// We are trying to connect to database at the start of our app and if it fails we exit       the process
var db = require('./db');
db.connectDatabase(function(){
  // your other code
})

//a.js
var db = require('./db');
//you can access your client here to perform database operations like that
db.client

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接