Within my collection of meals, there is a specific document I am working with:
# Meals collection
{
name: "burger",
tag: ObjectId(63d6bb22972f5f2fa97f1506),
}
Now, as I navigate through my React application, I find myself needing to send a query to my backend API.
To achieve this, I crafted a request that looks something like this:
const tagId = "63d6bb22972f5f2fa97f1506"
const queryString = `http://localhost:3001/v1/meals?tag=${tagId}`
sendQuery(queryString)
This query travels to the server following a RESTful pattern:
http://localhost:3001/v1/meals?tag=63d6bb22972f5f2fa97f1506
When it reaches the back-end, I handle the search parameters in this manner:
// # nodejs server-side
// # using expressjs
// # and using mongoose
api.get('/meals', async (req, res, next)=> {
const res = await MealModel.find(req.query) // req.query = { tag: "63d6bb22972f5f2fa97f1506" }
res.status(200).json({
status: 'success'
data: res
})
})
Despite my efforts, the query returns an empty array []
, due to the mismatch between the tag
type being an object ID instead of a string.
Your req.query.tag
is currently receiving a string rather than an object ID.
The question arises: how can one transmit an object ID from the front-end to the back-end via JSON?
It may seem perplexing, but fear not! Let's explore potential solutions together.