我将db-conn.js
我的存储db connection
在 a 中function
,然后将require
其存储在create.js
文件中call
。
我想要的是pass
将其余代码作为callback
它的一部分,以便首先将其connects
发送到数据库,然后执行insertion
.
由于我不太擅长回调,我不知道该怎么做。请你帮助我好吗?
所以这是 db-conn.js:
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))
})
}
在 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 =
{ } ...
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句