[英]How to define mongoose _id in TypeScript interface?
I'm using Mongoose and TypeScript with the interface+ class +schema approach .我将 Mongoose 和 TypeScript 与 interface+ class +schema 方法一起使用。
What is the canonical way to store the _id
field?存储
_id
字段的规范方法是什么?
I know the db stores it as a bson ObjectID
.我知道数据库将其存储为 bson
ObjectID
。 But I've seen some examples using string
and others using mongoose's ObjectId
, and then converting between them for various reasons - so I'm unsure which to use.但是我已经看到了一些使用
string
的示例和其他使用猫鼬的ObjectId
的示例,然后由于各种原因在它们之间进行转换 - 所以我不确定使用哪个。
interface Animal {
_id: ?type?; // ?
name: string;
}
Is it advisable to use是否建议使用
string
mongoose.Types.ObjectId
mongodb.ObjectID
bson.ObjectID
Also, assuming it is correct to use objectid - I want to avoid taking a dependency on mongoose in the interface file.另外,假设使用 objectid 是正确的——我想避免在接口文件中依赖 mongoose。 Is it safe/advisable to use the
bson
package's ObjectID
instead - are they equivalent?改用
bson
包的ObjectID
是否安全/可取 - 它们是否等效?
You can extend your interface with mongoose.Document
.您可以使用
mongoose.Document
扩展您的界面。 Your interface will be come你的界面会来
interface Animal extends mongoose.Document {
name: string;
}
Usage:用法:
export let AnimalSchema = mongoose.model<Animal>('animal', schema, 'animals');
let animal = await AnimalSchema.find({_id: "id"}).exec();
// animal._id / animal.name
you can do this你可以这样做
import { ObjectId } from 'mongoose';
interface Animal {
_id: ObjectId
name: string
}
Taken from the mongoose documentation :取自猫鼬文档:
Types
from mongooseTypes
_id
_id
import { Types } from 'mongoose';
interface Animal {
_id: Types.ObjectId;
name: string;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.