在db-conn.js中,我将db connection存储在function中,然后将其保存在create.js文件中,并将其用于call。
我想要的是将其余的代码作为对其的pass作为一个callback,这样它首先可以将connects放到数据库中,然后再执行insertion。
因为我不太擅长回调,所以我不知道该怎么做。你能帮帮我吗?
所以这就是db-conn.js. So:
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这是create.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))
})
}发布于 2017-11-08 16:41:22
当连接在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中,您需要向mongo.doConnection(...)添加一个回调函数作为参数,连接完成后将调用这个参数(fcallback被调用)
通过此回调,您可以确保连接完成后将调用createStudent。
mongo.doConnection( (err, db) => {
if(err){
console.error("error connection to db: " + err;
return;
}
createStudent = () => {
var jStudent =
{ } ...
});https://stackoverflow.com/questions/47184043
复制相似问题