我正在使用 express 和 node-postgres ( https://github.com/brianc/node-postgres ) 构建一个节点应用程序。我只想建立一次数据库客户端连接,我希望能够从不同的模块访问这个数据库连接。做这个的最好方式是什么?我试图只导出数据库连接,而不是整个快速应用程序。本质上,跨节点应用程序导出和访问对象的最佳方式是什么?
我已经检查了这个类似的问题,但它似乎特定于猫鼬。
我正在使用 express 和 node-postgres ( https://github.com/brianc/node-postgres ) 构建一个节点应用程序。我只想建立一次数据库客户端连接,我希望能够从不同的模块访问这个数据库连接。做这个的最好方式是什么?我试图只导出数据库连接,而不是整个快速应用程序。本质上,跨节点应用程序导出和访问对象的最佳方式是什么?
我已经检查了这个类似的问题,但它似乎特定于猫鼬。
没有所谓的“最好的方法”。如果您需要在不同模块之间使用相同的对象,则必须将其包装在一个模块中。像这样的东西:
//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()
嗨,我正在研究解决方案,从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)
});
});
你可以做这样的事情..
//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