Tanmoy Basak
Tanmoy Basak

Reputation: 142

ObjectId converting to strings in api, nodejs to reactjs

I have a simple API, that sends data in a response

Food.aggregate([{
    $match: {
        res_id: restaurant._id
    }
}, {
    $group: {
        _id: "$category",
        foods: {
            $push: "$$ROOT"
        }
    }
}], function(err, foods) {

    if (err)
        res.json({
            error: "error"
        });
    else
        res.json(foods);

});

However, when I read the data using axios in my React app, The objectIds get converted to strings in my front end React app.

Now I could not find any resource on the type of data types that can be passed over HTTP or any other restrictions. Can anyone point me to any resource or tell me if this is the way HTTP works.

Upvotes: 1

Views: 703

Answers (1)

Kapil
Kapil

Reputation: 138

JSON.stringify() will recursively call toJSON() method to get JSON-safe string representation of the object that you need to pass over HTTP from your server to your frontend app during serialization in javascript.

ObjectID will be converted to 24 byte hex string during serialization: ObjectID.prototype.toJSON

Upvotes: 1

Related Questions