![](/img/trans.png)
[英]How to define a named array of objects in an interface with TypeScript?
[英]How to define mongoose _id in TypeScript interface?
我將 Mongoose 和 TypeScript 與 interface+ class +schema 方法一起使用。
存儲_id
字段的規范方法是什么?
我知道數據庫將其存儲為 bson ObjectID
。 但是我已經看到了一些使用string
的示例和其他使用貓鼬的ObjectId
的示例,然后由於各種原因在它們之間進行轉換 - 所以我不確定使用哪個。
interface Animal {
_id: ?type?; // ?
name: string;
}
是否建議使用
string
mongoose.Types.ObjectId
mongodb.ObjectID
bson.ObjectID
另外,假設使用 objectid 是正確的——我想避免在接口文件中依賴 mongoose。 改用bson
包的ObjectID
是否安全/可取 - 它們是否等效?
您可以使用mongoose.Document
擴展您的界面。 你的界面會來
interface Animal extends mongoose.Document {
name: string;
}
用法:
export let AnimalSchema = mongoose.model<Animal>('animal', schema, 'animals');
let animal = await AnimalSchema.find({_id: "id"}).exec();
// animal._id / animal.name
你可以這樣做
import { ObjectId } from 'mongoose';
interface Animal {
_id: ObjectId
name: string
}
取自貓鼬文檔:
Types
_id
import { Types } from 'mongoose';
interface Animal {
_id: Types.ObjectId;
name: string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.