Actually, I want to get data and insert into my DB. If it exists, doesn't insert the data. And display the data from DB using the ID.
After Inserting the new data, I have to display the new data.
I'm using Nodejs and MongoDB with a third-party API to fetch data.
Journals.findOne({pubmedId: pubmedID}, function(err, results) {
if (err) {
console.log(err);
res.status(500);
} else if (results) {
res.status(400);
res.send(results);
console.log("PudmedID should be unique. Pubmed Data already exists! " + pubmedID);
} else {
newMedjournalData.save((err, Journals) => {
if (err) {
console.log(err);
res.status(500);
res.send({
"error": "Can't Insert the data " + pubmedID
});
console.log("Can't Insert the data - " + err + " - " + pubmedID);
} else {
res.status(200);
// res.send({ "success": "Successfully Inserted data " + pubmedID });
console.log("Successfully Inserted data " + pubmedID);
var getData = getpubMedData(pubmedID);
console.log(getData);
res.send(getData);
}
});
}
});
I have created a function - getpubMedData
to get data from DB after inserting the data.
But I got undefined from console.log(getData);
I refered a Stackoverflow answer.
And added a module - med_data.
const Journals = require('./models/journals');
var med_data = function (pubmedID) {
console.log(pubmedID);
Journals.findOne({ pubmedId: pubmedID }, function (err, results) {
if (err) {
console.log(err);
return {"error": err};
} else if(results){
console.log(results);
return results;
}
});
}
module.exports = med_data;
and added following,
const getpubMedData = require('../med_data');
But here,
var getData = getpubMedData(pubmedID);
console.log(getData);
res.send(getData);
I got again Undefined
If it is a wrong way, Please suggest me the best way. If my logic is wrong, Please help me to fix the issue.
答案 0 :(得分:2)
I/O calls happens async in js. You must provide a way to recover data once async code ends. You can do this using callbacks or promises.
For callback do something like:
var med_data = function (pubmedID, callback) {
console.log(pubmedID);
Journals.findOne({ pubmedId: pubmedID }, function (err, results) {
if (err) {
console.log(err);
return {"error": err};
} else if(results){
console.log(results);
callback(results);
}
});
}
and
// var getData = getpubMedData(pubmedID)
getpubMedData(pubmedID, function(response) {
console.log(response);
res.send(response);
});