Imagine a straightforward user database setup:
// db.ts
export interface User {
_id: mongodb.ObjectId;
username: string;
password: string;
somethingElse: string;
}
// user.ts
import {User} from "../db"
router.get("/:id", async (req, res) => {
const id = req.params.id;
// user._id is a mongodb.Object.
const user: User = await db.getUser(id);
res.send(user);
});
// index.ts
// code that will runs on browser
import {User} from "../../db"
$.get('/user/...').done((user: User) => {
// user._id is string.
console.log(user._id);
});
Everything functions smoothly until attempting to utilize this structure in client-side scripts. This occurs because the _id
of the user converts to a hex string when sent as JSON from the server. When changing _id
to mongodb.ObjectId | string
, the behavior becomes strange.
https://i.sstatic.net/FmNmW.png