[英]How should I define interfaces of documents when using Typescript and Mongodb?
考慮一個簡單的用戶集合:
// 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);
});
直到我要在客戶端代碼中使用此接口之前,它都可以正常工作。 因為當用戶_id
從服務器作為json傳輸時,它變為十六進制字符串。 如果我將_id
設置為mongodb.ObjectId | string
mongodb.ObjectId | string
,行為變得很奇怪。
您可以嘗試以一種聰明的方式將它們分開:
interface User {
username: string;
password: string;
somethingElse: string;
}
export interface UserJSON extends User {
_id : string
}
export interface UserDB extends User {
_id : mongodb.ObjectId
}
然后使用UserJSON(client)或UserDB(server-side)。
感謝@drinchev。 而且我已經找到了使用泛型的更好方法:
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.