I keep getting this error from this code and have no idea why {"Error: CastError: Cast to ObjectId failed for value \"confirmed\" at path \"_id\" for model \"Order\""}
As you can see I am not even using the objectID in this query... I dont know why it is returning this
router.get("/orders/confirmed", async (req, res) => {
try {
const confirmedOrders = await Order.find({ isConfirmed: false })
res.json(confirmedOrders)
} catch (err) {
res.status(400).json("Error: " + err)
}
})
adding my comment as answer because im 99% sure thats it. I have been there....
it looks to me like there is a route above this one one thats more like "/: model/:id". Its finding that route params first. Move that route below this one in your code. That way this specific route will match first then the other one will match if other words\ids are used.
More general note. Always sort route most specific to least specific to try to avoid this. You want /really/specific/ to come before /:something/:else because the handler with match the vars like so if they are in the wrong order... as you see in your current situation.
req.params.something === "really"
req.params.else === "specific"
Related
i just need someone to tell me what is wrong with my code. This is it.
const getSingletask = async (req, res)=>
{
try{
const task = await Task.findOne({_id:req.params.id})
if(!task){
return res.json({msg:`No such task with and id of ${req.params.id}`})
}
res.json({task})
}catch(error){
res.json({msg:error})
}
}
Basically what the code is doing is that whenever the function excutes, it finds one particular item using its ID. The IF statement is the first error handler. It is meant to return that message if the ID cannot be found but it keeps bringing up an error anytime i test it out. I think my code is correct so can someone tell me what i did wrong?
You seem to be using mongoose. Mongoose saves db objects by way of a wrapper called ObjectId, that accepts exactly 24 hex characters. Because the ID you are inputting into it is not 24 hex characters, mongoose fails to cast it (meaning to use the wrapper), and so, throws an error.
I know there are other posts with similar issues, but none of the suggestions I've tried have worked.
The following works if the _id is valid, but throws an unhandled promise rejection error if it isn't:
const Movie = mongoose.model(`Movie`, movieSchema);
router.get(`/api/movies/:id`, async (req, res) => {
let movie = await Movie.findById(req.params.id);
if(!movie) {
res.status(404).send(`Movie with given ID not found.`);
return;
};
});
Per the docs, it looks like findById() is supposed to return null if the id can't be found, so I'm not sure what the issue is. Do I need to put a catch block somewhere and put the 404 in there? I've tried putting it everywhere I can think to.
As per the Mongoose documentation...
Model.findById()
Returns:
«Query»
Looking into the Query API, when used like a Promise, it will invoke the Query.prototype.then() implementation
Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error.
To use this, you would need something like
try {
const movie = await Movie.findById(req.params.id)
// do stuff with movie
} catch (err) {
res.sendStatus(404)
}
use .then() and .catch() will sort your issue.
function checkFamilyStatus() keeps returning undefined for some reason, when it should be returning a boolean value from a mongodb collection.
A bit of context here - I decided to separate the logic part from the router methods like get and post methods, so as to make it look clean and understandable like in functional programming. So I put the logic part in functions and invoke them inside the router methods, but it doesn't work out. Besides, I don't know if this is a good practice or not. Wouldn't it be much easier to read if done like this, instead of say, putting a whole bunch of code in one place?
I've been stuck on this piece of code for a while. I am a bit confused on the working of asynchronous JS as a whole. I did some research, but still don't understand why this wouldn't work. Could someone clarify this up for me?
// post method
router.post("/create", ensureAuthenticated, async(req, res) => {
let userID = req.user.id;
console.log(await checkFamilyStatus(userID)); // but returns undefined
// rest of the code
}
// check family status
checkFamilyStatus = async userID => {
Account.findOne({
_id: userID
}, (err, account) => {
return account.hasFamily; // should return boolean value ?
});
};
Assuming the logic behind account.hasFamily is correct, then you need to await for the return, so it should be return await account.hasFamily;
When trying to fetch all the posts by a user id, cosmos DB only return an empty array, but when using mongo DB through atlas, it returns all the posts by that user. What am i doing wrong.
exports.postsByUser = (req, res) => {
Post.find({ postedBy: req.profile._id })
.populate("postedBy", "_id name")
.select("_id title body created likes")
.sort("_created")
.exec((err, posts) => {
if (err) {
return res.status(400).json({
error: err
});
}
res.json(posts);
});
`enter code here`};
I receive a http status of 200, but with just an empty array. and when i try fetching all the posts by all users it returns.
I know this might not be "the answer" but it is a suggestion which will bring others to the correct answer in their case.
For those who run into bugs like these, the easiest way to find out what is happening and which step is making the unexpected return is to comment out all the pipeline steps, in this case, populate, select and sort. Then debug from there - if it returns anything, if there is no result you can start from your match case (find), if it does return you can move to next pipeline step and so on.
Taking some time debugging yourself will make you understand your code better, and you will find the answer yourself faster than waiting for someone on stackoverflow to give u suggestions.
I'm executing post from react and after that I have some calculations on my back end. How to execute get to show the result on my front end after post and calculation ?
I think I got your question, albeit vague.
But,
1) You want to post a data to some route. The route maybe gives a success response or an error or maybe some different data, but it internally does some processing maybe adds some row to a db table.
2) You want to fetch the current state of the db table(I am assuming table, may be anything).
If this is the scenario, you can do what you are doing just add a get call in the chain.
axios.post('/api/OddsCalculator', newGame)
.then(games => {
// this means you got your game
this.setState({ games }, () => console.log(), games);
//now add one get request as well
return axios('/api/getSomeData');
})
.then((data)=>{
//this data is from the GET call
this.setState({ data })
})
.catch(err => this.setState({
errors: err.response.data
}))
Hope this is a fair assumption, but feel free to edit the answer when you get your solution.
Refer Promise Chaining here: https://javascript.info/promise-chaining
You call it on the success of the previous method. You use nested calls. Please find below example where there should be two methods : yourPostMethod & yourGetMethod defined before you call them.
function handler () {
return yourPostMethod()
.then(yourGetMethod)
.then((result) => {
console.log(result)
return result
})
}
You have express tag in question, so I am assuming you're using that.
With express, redirect works beautifully. I use it all the time
Say:
app.post('/somePOSTpath', (req, res) => {
// Do Some stuff
res.redirect('/somepath');
})
This will direct your backend to somepath at the end.