HTTP .get() method does not respond with anything - mongodb

I am trying to use Express + MongoDB building React app.
I was able to post some documents to MongoDB and delete them. Currently, I'm trying to figure out how to get them using HTTP .get() method.
I have these routes:
router.post('/totalbalance', (request, response) => {
const totalBalance = new TotalBalanceModelTemplate({
totalBalance:request.body.totalBalance,
});
totalBalance.save()
.then(data => {
response.json(data);
})
.catch(error => {
response.json(error);
});
});
router.get('/totalbalance', (request, response) => {
console.log("Response ", response);
});
This is axios request:
useEffect(() => {
console.log("Using get() method here");
axios.get('http://localhost:4000/app/totalbalance')
}, []);
However, it does not return anything (only 'Using get() method here' gets printed out to the console).
What am I missing here?
Thanks in advance!

Related

Mongoose .find Query doesn't return collection data

I have the following code to get all the data from a collection:
app.get('/', (req, res) => {
Question.find({}, (err, found) => {
if (!err) {
console.log(found)
res.send(found);
} else {
console.log(err);
res.sendStatus("Some error occured!")
}
}).clone().catch(err => console.log("Error occured -- " + err));
});
Using debug, I'm seeing that I'm connected to my database and also that I'm sending the appropriate query:
Mongoose: TopicsDB.find({}, { projection: {} })
However, none of the data from the collection is being returned.
This is probably because you are not using async and await in your call to the database. Every call to the database is by default an asynchronous call and hence it needs to have async and await for it to work properly.
app.get('/', async (req, res) => {
await Question.find({}, (err, found) => {
if (!err) {
console.log(found)
res.send(found);
} else {
console.log(err);
res.sendStatus("Some error occured!")
}
}).clone().catch(err => console.log("Error occured -- " + err));
});
Try this. Hope it helps.

koa doesn't render a page (404) after mongodb request

I am trying to render a page with something I load from MongoDB:
router.get('/messages', async (ctx, next) => {
await MessageModel.find()
.then((result:any) => {
ctx.render('index', {
title: 'Messages',
messages: result
})
});
});
I got 404 message after I go to /messages but it works fine when I render it without approaching to DB:
router.get('/messages', async ctx => {
await ctx.render('index', {
title: 'Messages'
})
});
Sorry for my 'noob' question, I am just making my first steps into coding. Thanks for help.
You should await for models result or consume them with .then(), not both at the same time. Try this:
router.get('/messages', async (ctx, next) => {
let result = await MessageModel.find()
await ctx.render('index', {
title: 'Messages',
messages: result
})
})

async function returns Promise { <pending> }

I am trying to write a function that takes a URL and returns the engagement stats from Facebook Graph API against that URL. But I am facing trouble as my function is just giving me Promise { <pending> } as output.
Here is my code:
const getFacebookStats = async (link, ACCESS_TOKEN) => {
try {
const resp = await axios.get(
`https://graph.facebook.com/v12.0/?id=${link}&fields=engagement&access_token=${ACCESS_TOKEN}`
);
return resp;
} catch (err) {
// Handle Error Here
console.error(err);
}
};
Any help would be much appreciated.
Call your function like this:
getFacebookStats(link, ACCESS_TOKEN).then(response => {
console.log(response);
}).catch(error => {
console.error(error);
});
Or you could call it using await inside an async function.
Check this answer for a more detailed explaination of Promises in javascript.

Axios get request with parameter is not working

I am passing a parameter to the axios get request. It works on postman properly but does not work with my code. I don't know where I am making a mistake.
I want only one specific data from db but I am receiving all the data in available in the collection. But with postman I get the desired data
backend route :
router.get('/displayUser', (req,res) => {
const query = user = req.body ;
Services.find(query)
.exec((err, services) => res.json(services))
})
axios call : I tried two different ways and both didn't work
method 1:
getData: async function () {
const user = this.userId
console.log(user)
let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { user }})
console.log(res.data);
}
method 2:
getData: async function () {
var data = JSON.stringify({"user":this.userId});
console.log(data)
var config = {
method: 'get',
url: 'http://localhost:5000/api/services/displayUser',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
When I get the data in console I am getting all 3 objects available in collection instead of the specific one related to the user Id
Screenshot
But in postman It works as desired
screenshot
I do this as following:
when I need a get :
app.get('/detail/:id', function (req, res) {
//console.log(req.params.id);
var url=urlDetail + "/" + req.params.id;
axios.get(url)
.then(function (response) {
// result=response.data;
res.render('database', { title: 'Detail' , dbs: response.data ,Version:pjson.version});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
//console.log("ici always");
});
});
and when i need to post (req.body is a json):
app.post('/carto/demande', function (req, res) {
let data;
console.log(req.params);
console.log(req.body);
var url=urlCartoDemande;
axios.post(url,req.body)
.then(function (response) {
data=response.data;
res.render('carto', { title : 'Demande' ,Version:pjson.version,mode:"resultat",data:data } );
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
});

Mongoose not fetching data until I refresh the database connection

I am trying to re-fetch the data from MongoDB using mongoose whenever a user reloads the page. However, the old data stays there and the new data doesn't get fetched until I restart the server.
Here is the router:
router.post("/dashboard", (req, res) => {
const userId = req.body.userId;
User.findOne({ _id: userId }, (err, users) => {
if (err) {
console.log(err);
res.status(500).send();
} else {
router.get("/dashboard", (req, res, next) => {
const leagues = [users.leagues.premium, users.leagues.free];
if (err) return next(err);
res.status(200).send(leagues);
});
}
});
});
And here is the Actions (Redux):
export const fetchLeagues = userId => dispatch => {
axios.post("/api/leagues/dashboard", userId).then(
setTimeout(function() {
axios.get("/api/leagues/dashboard").then(leagues => {
dispatch({
type: GET_LEAGUES,
payload: leagues
});
});
}, 50)
);
};
The data must be fetched from a specific user, so that's why I am posting the user Id, then getting the data back. Not sure if this is the best way of doing this.
Just to clarify, I am using the MERN stack with redux and axios to execute this. I tried to use this: MongoDB does not refresh data automatically?, but I still can't get this thing to refresh/re-fetch the data when the router is called again. Thanks.
Doing a POST request then a GET request seems unnecessary here as you can just return the data in a single request.
The reason why the data is being persisted is because when you declare the router.get('/dashboard') route you are permanently hardcoding that route to have the values from the first request.
It's probably best to use a GET request, as that is what you are trying to do.
e.g.
router.get("/dashboard/:userId", (req, res) => {
const userId = req.params.userId;
User.findOne({ _id: userId }, (err, users) => {
if (err) {
console.log(err);
res.status(500).send();
} else {
const leagues = [users.leagues.premium, users.leagues.free];
if (err) return next(err);
res.status(200).send(leagues);
}
});
});
// Where userId is now a string
export const fetchLeagues = userId => dispatch => {
axios.get(`/api/leagues/dashboard/${userId}`).then(leagues => {
dispatch({
type: GET_LEAGUES,
payload: leagues
});
});
};