[英]How should I define interfaces of documents when using Typescript and Mongodb?
Consider a simple user collection: 考虑一个简单的用户集合:
// 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);
});
It works perfectly until I want to use this interface in client codes. 直到我要在客户端代码中使用此接口之前,它都可以正常工作。 Because the _id
of user becomes a hex string when tranmitted as json from server. 因为当用户_id
从服务器作为json传输时,它变为十六进制字符串。 If I set _id
to be mongodb.ObjectId | string
如果我将_id
设置为mongodb.ObjectId | string
mongodb.ObjectId | string
, the behavior gets wierd. mongodb.ObjectId | string
,行为变得很奇怪。
You can try to separate them in a smart way : 您可以尝试以一种聪明的方式将它们分开:
interface User {
username: string;
password: string;
somethingElse: string;
}
export interface UserJSON extends User {
_id : string
}
export interface UserDB extends User {
_id : mongodb.ObjectId
}
and later take either UserJSON ( client ) or UserDB ( server-side ). 然后使用UserJSON(client)或UserDB(server-side)。
Thanks to @drinchev. 感谢@drinchev。 And I have figured out a better way to do it, using generics: 而且我已经找到了使用泛型的更好方法:
interface User<IdType> {
_id: IdType;
username: string;
posts: Post<IdType>[];
}
interface Post<IdType> {
_id: IdType;
text: string;
}
export type UserDB = User<mongodb.ObjectID>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.