我正在处理不同模块的任务。
我需要为每个模块提供一个通用的mongodb连接..
如何在一些模块中编写并在此中使用,因为在其他一些模块中也需要数据库连接......
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbo = db.db("mydb");
});
router.post('/', function(req, res) {
dbo.collection("customers").find({"userid":req.body.userid}).toArray(function(err, result) {
if (err) throw err;
if(result.length>0){
res.send("username already taken please enter differnt username ")
}
else if(req.body.fname==undefined||(!validator.isAlpha(req.body.fname))){
res.send("please enter only alphabets as fname ")
}
else if(req.body.lname==undefined||(!validator.isAlpha(req.body.lname))){
res.send("please enter only alphabets as lname ")
}
else if(req.body.userid==undefined||(!validator.isAlphanumeric(req.body.userid))){
res.send("please enter only alphanemric as user name ")
}
else if(req.body.pwd==undefined||req.body.pwd.length<6){
res.send("please enter atleast 6 charcaters as password ")
}
else{
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(req.body.pwd, salt);
req.body.pwd=hash;
dbo.collection("customers").insertOne(req.body, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
});
res.send(req.body);
}
});
});
module.exports = router;
答案 0 :(得分:0)
使用可以使用节点导出和导入,也可以在其他模块中使用mongodb连接实例, 假设dbo是您想要存储mongodb连接的变量
export let dbo;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbo = db.db("mydb");
});
您可以将db连接分配给dbo变量,并在您想要的任何模块中使用它
答案 1 :(得分:0)
您必须为您的连接创建一个中间件,然后将db
对象分配给您的请求对象(在您的情况下为req
)
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
router.use( (req,res,next) => {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
req.dbo = db.db("mydb");
next();
});
})
在您的router.post("/", ...)
req.dbo.collection(...)
答案 2 :(得分:0)
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.conection=function(){
if(dbo!=null) return
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbo = db.db("mydb");
});
}
exports.get = function (){
return dbo;
}
我尝试了这个,当我需要这个时,我使用get方法