我有db-conn.js
我将db connection
存储在function
中,然后require
将其存储在create.js
文件中call
。
我想要的是将pass
代码的其余部分callback
作为connects
,以便首先insertion
到数据库,然后执行var mongo = {}
/**************************************************/
mongo.doConnection = (fcallback) => {
mongo = require('mongodb').MongoClient
global.db = null
sDatabasePath = 'mongodb://localhost:27017/kea'
global.mongoId = require('mongodb').ObjectID
/**************************************************/
mongo.connect(sDatabasePath, (err, db) => {
if (err) {
console.log('ERROR 003 -> Cannot connect to the database')
return false
}
global.db = db
console.log('OK 002 -> Connected to the database')
})
}
/**************************************************/
module.exports = mongo
。
由于我不善于回调,我不知道该怎么做。你能帮我吗?
这就是db-conn.js:
var mongo = require(__dirname + '/db-conn.js')
/**************************************************/
mongo.doConnection()// I am not sure what to do here
createStudent = () => {
var jStudent =
{
"firstName": "Sarah",
"lastName": "Jepsen",
"age": 27,
"courses": [
{
"courseName": "Web-development",
"teachers": [
{
"firstName": "Santiago",
"lastName": "Donoso"
}
]
},
{
"courseName": "Databases",
"teachers": [
{
"firstName": "Dany",
"lastName": "Kallas"
},
{
"firstName": "Rune",
"lastName": "Lyng"
}
]
},
{
"courseName": "Interface-Design",
"teachers": [
{
"firstName": "Roxana",
"lastName": "Stolniceanu"
}
]
}
]
}
global.db.collection('students').insertOne(jStudent, (err, result) => {
if (err) {
var jError = { "status": "error", "message": "ERROR -> create.js -> 001" }
console.log(jError)
}
var jOk = { "status": "ok", "message": "create.js -> saved -> 000" }
console.log(jOk)
console.log(JSON.stringify(result))
})
}
这是create.js:
module.exports = {
function1: functions(parm1, callback){
if (checkParm1(parm1)) {
//do something
}else{
//do something else
}
callback();
}
};
function checkParm1(parm1){
return ( parm1 === 'abc' );
}
答案 0 :(得分:1)
在db-conn.js中完成连接后,您需要调用fcallback
回调。
mongo.connect(sDatabasePath, (err, db) => {
if (err) {
console.log('ERROR 003 -> Cannot connect to the database')
return fcallback(err, null);
}
global.db = db
console.log('OK 002 -> Connected to the database')
return fcallback(null, db);
})
然后在create js中你需要添加一个回调函数作为mongo.doConnection(...)
的参数,当连接完成时调用它(调用fcallback)
使用此回调,您可以确保在连接完成时调用createStudent
。
mongo.doConnection( (err, db) => {
if(err){
console.error("error connection to db: " + err;
return;
}
createStudent = () => {
var jStudent =
{ } ...
});