我正在做一个有不同模块的任务。
我需要为每个模块建立一个通用的mongodb连接。
如何在某些模块中写入并在其中使用,因为在其他一些模块中也需要db连接.
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;发布于 2018-03-17 06:31:42
可以使用节点导出和导入,也可以在其他模块中使用mongodb连接实例,假设dbo是要存储mongodb连接的变量。
export let dbo;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
dbo = db.db("mydb");
});您可以将db连接分配给dbo变量,并在任意模块中使用它。
https://stackoverflow.com/questions/49333091
复制相似问题