Answer the question
In order to leave comments, you need to log in
How to return a value from a module?
How can I return the value of res to the main file from the module, if possible, throw off the finished code and explain what the problem is, now it returns undefined, preferably promisom
module code
function insertChat(url){
MongoClient.connect(url,options, function(err, client){
if(err) throw err;
const db = client.db('chat');
const collection = db.collection('chatmessage');
if(err) return console.log(err);
collection.findOne(function(err, result){
if(err) throw err;
var res = result.chatmessage;
console.log(res);//test
return res;
client.close();
});
});
}
database = require('./dbtest.js');
var urlDb = 'mongodb://localhost:27017/chat';
console.log(insertChat(urlDb));
Answer the question
In order to leave comments, you need to log in
You need to use the same pattern that is implemented in the MongoClient.connect(...) function:
function insertChat(url, callback){
MongoClient.connect(url,options, function(err, client){
...
collection.findOne(function(err, result){
...
callback(res);
});
});
}
database = require('./dbtest.js');
var urlDb = 'mongodb://localhost:27017/chat';
insertChat(urlDb, result => console.log(result));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question