MongoDB GET request returning empty array - mongodb

I am using nextjs and mongodb. I performed a GET request but Mongodb returned an empty array. The POST request before that has no problem. Both POST and GET request have status 200 tho.
if (req.method === 'GET') {
try {
const getData = await db.collection(peopleData).find({}).toArray(); // peopleData is from query
res.json(getData);
res.status(200).json({ message: getData });
} catch (error) {
return res.status(500).json({ message: error });
}
}
Thanks in advance

Related

How to pass array to graphql mutation using axios

I have created a mutation that accepts an array of objects. I tested it with an apollo client and it's working fine in my apollo client query is looks like this.
mutation {
createStudent(createStudentInput: [{
name:"Jhone Doe"
email:"Jhonedoe#gamil.com"
dob:"1996-01-21"
},
{
name:"Jhone Doe1"
email:"Jhonedoe1#scl.com"
dob:"2000-01-22"
}
]) {
id,
name
dob
}
}
But when I try to perform the mutation using Axios it's throwing an error Request failed with status code 400.this is the qraphql query I'm passing to the Axios. I can't figure out what I am doing wrong here. Please note that records is an array of objects
const graphqlQuery = {
query: `
mutation {
createStudent(createStudentInput:${records}) {
id,
name
dob
}
}`,
variables: {
},
};
My Axios request
try {
const results = await axios({
url: endpoint,
method: 'post',
headers: headers,
data: graphqlQuery,
});
return results;
} catch (error) {
console.log(`error occured:${error}`);
}
}

Nuxt axios - how to reject a success response to error

I define axios like below
$axios.onResponse((response) => {
if (response.data.status == 500}
return Promise.reject(response)
}
})
$axios.onError((err) => {
console.log(err)
})
and in fetch i call
async fetch () {
await this.$axios.$get('myapi')
}
but i get error like
RangeError
Maximum call stack size exceeded
I try to reject a success response to error but it not working in ssr. How to fix that thank.
Generally, using try-catch statements are preferred over event handlers (where appropriate).
Try something like this:
async fetch() {
try {
const response = await this.$axios.$get('myapi');
if (response.data.status == 500) {
throw new Error("Some error message");
} else {
// Success action here
}
} catch(err) {
console.log(err);
}
}
Is there any particular reason you're returning a rejected Promise when you get a 500 error? Is there any reason not to throw a generalized error message instead?

How to get axios error response INTO the redux saga catch method

With axios the code is:
export const createBlaBla = (payload) => {
return axios.post('/some-url', payload)
.then(response => response)
.catch(err => err);
}
And then I'm using this with redux-saga like this:
function* createBlaBlaFlow(action) {
try {
const response = yield call(createBlaBla, action.payload);
if (response) {
yield put({
type: CREATE_BLA_BLA_SUCCESS
});
}
} catch (err) {
// I need the error data here ..
yield put({
type: CREATE_BLA_BLA_FAILURE,
payload: 'failed to create bla-bla'
});
}
}
In case of some error on the backend - like invalid data send to the backend - it returns a 400 response with some data:
{
"code":"ERR-1000",
"message":"Validation failed because ..."
"method":"POST",
"errorDetails":"..."
}
But I don't receive this useful data in the catch statement inside the saga. I can console.log() the data in the axios catch statement, also I can get it inside the try statement in the saga, but it never arrives in the catch.
Probably I need to do something else? ... Or the server shouldn't return 400 response in this case?
So, I came up with two solutions of this problem.
===
First one - very dump workaround, but actually it can be handy in some specific cases.
In the saga, right before we call the function with the axios call inside, we have a variable for the errors and a callback that sets that variable:
let errorResponseData = {};
const errorCallback = (usefulErrorData) => {
errorResponseData = usefulErrorData;
};
Then - in the axios method we have this:
export const createBlaBla = (payload, errCallback) => {
return axios.post('/some-url', payload)
.then(response => response)
.catch(err => {
if (err && err.response.data && typeof errCallback === 'function') {
errCallback(err.response.data);
}
return err;
});
}
This way, when we make request and the backend returns errors - we'll call the callback and will provide the errors from the backend there. This way - in the saga - we have the errors in a variable and can use it as we want.
===
However, another solution came to me from another forum.
The problem I have is because in the method with the axios call I have catch, which means that the errors won't bubble in the generator. So - if we modify the method with the axios call like this:
export const createBlaBla = (payload) => {
return axios.post('/some-url', payload)
}
Then in the catch statement in the saga we'll have the actual backend error.
Hope this helps someone else :)
In your API call you can do the following:
const someAPICall = (action) => {
return axios.put(`some/path/to/api`, data, {
withCredentials: true,
validateStatus: (status) => {
return (status == 200 || status === 403);
}
});
};
Please note the validateStatus() part - this way when axios will encounter 200 or 403 response, it will not throw Error and you will be able to process the response after
const response = yield call(someAPICall, action);
if (response.status === 200) {
// Proceed further
} else if (response.status === 403) {
// Inform user about error
} else {
...
}

Mongodb errors specific code handling

I am trying to output specific messages on specific responses.
Here is my code:
.post(function(req, res) {
var user = new User(req.body);
user.save(function(err) {
if(err) {
if(err.code == 11000)
res.status(409).json(customHTTPcodeReponses.exists(req.body.email));
};
User.findById(user._id, function(err, createdUser) {
res.status(201).json(customHTTPcodeReponses.created(createdUser));
});
});
});
Flow:
Posting data. I get 201.
Posting same data again. I get 409.
Posting same data again. I get "Could not get any response (POSTMAN)"
Console error:
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
[nodemon] app crashed - waiting for file changes before starting...
What could cause this?
Add the User.findById code within an else statement.
user.save(function(err) {
if(err) {
if(err.code == 11000)
res.status(409).json(customHTTPcodeReponses.exists(req.body.email));
}else{
User.findById(user._id, function(err, createdUser) {
res.status(201).json(customHTTPcodeReponses.created(createdUser));
});
}
});
or add a return to the 1st response:
if(err.code == 11000)
return res.status(409).json(customHTTPcodeReponses.exists(req.body.email));

Connect to rest API with Meteor

I want to connect to rest API with auth in Meteor but when I run through their docs cant see anything stuff for connecting to rest API. All I can see it that the HTTP request. So, I tried using it. I need to connect to this:
URL: http://lpgp-dev.mrkt.it/test/oauth/rest/testview2
key: 'mykey'
secret: 'my secret'
For now I have this lines of code:
from server:
Meteor.methods({
getArticles: function () {
check(q, String);
this.unblock();
try {
var result = HTTP.call("GET", "http://lpgp-dev.mrkt.it/test/oauth/rest/testview2",
{params: {key: 's86MopNFA6pwmBXQoEw8k5yBVAVjN8vz', secret: 'cKC2tpXP3ZRQvqAsobCPeK2jB4kjsDos'}});
return result;
} catch (e) {
// Got a network error, time-out or HTTP error in the 400 or 500 range.
return false;
}
}
});
from client which I called the method:
var getResponse = function(){
Meteor.call('getArticles', function (error, result) {
if (!error) {
var res = JSON.parse(result.content);
/*var _res = _(res.response.docs).toArray();*/
/*Session.set('numCount', res.response.numFound);
Session.set('news', _res);*/
console.log(res);
}else{
console.log(error);
}
});
}
When I run it return this error:
errorClass: Internal server error [500] of undefined
hope you can help me. Thanks...