[英]Mongoose and TypeScript - returned _id is in strange format
Have some strange response when querying MongoDB (via Mongoose) from TypeScript.从 TypeScript 查询 MongoDB(通过 Mongoose)时有一些奇怪的响应。
Having these two intrfaces:有这两个接口:
import { Document, Types } from "mongoose";
export interface IModule extends Document {
_id: Types.ObjectId;
name: string;
owner: number;
isMain: boolean;
url: string;
}
export interface IProject extends Document {
_id: Types.ObjectId;
name: string;
description: string;
owner: number;
modules: IModule[];
}
And these are Mongoose schemas and models:这些是 Mongoose 模式和模型:
import { IModule, IProject } from "../interfaces/mongo";
export const ModuleSchema = new mongoose.Schema({
name: { type: String, required: true },
owner: { type: String, required: false },
isMain: { type: Boolean, required: true },
url: { type: String, required: false },
});
export const ModuleModel = mongoose.model<IModule>("Module", ModuleSchema);
export const ProjectSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String, required: false },
owner: { type: Number, required: true },
modules: [ModuleSchema],
});
export const ProjectModel = mongoose.model<IProject>("Project", ProjectSchema);
Using model.find
to return all documents where the owner
is equal to 13使用model.find
返回owner
等于 13 的所有文档
await ProjectModel.find({ owner: 13 })
.select("-__v")
.lean()
.exec();
And this is what im getting in Postman as response.这就是我在 Postman 中得到的响应。 Not sure why _id
is back in such format.不知道为什么_id
又回到了这种格式。 I've tried to change the type of _id
in the interface but it always comes back like this我试图在界面中更改_id
的类型,但它总是像这样返回
{
"_id": {
"_bsontype": "ObjectID",
"id": {
"type": "Buffer",
"data": [
96,
173,
237,
68,
72,
243,
160,
124,
92,
93,
142,
242
]
}
},
"name": "whatever-repo",
"description": "",
"owner": 13,
"modules": [
{
"_id": {
"_bsontype": "ObjectID",
"id": {
"type": "Buffer",
"data": [
96,
174,
108,
154,
204,
174,
125,
138,
184,
56,
58,
227
]
}
},
"owner": "13",
"isMain": false,
"name": "whatever-repo-module4",
"url": "test/whatever-repo-module4"
},
...
The interface
in TypeScript is not checked in runtime - it is only checked in compile time. TypeScript 中的interface
未在运行时检查 - 它仅在编译时检查。 Thus, you can't simply change the runtime structure directly in interface
.因此,您不能简单地直接在interface
中更改运行时结构。
For this case, you can use .map(val => val.id =...)
if it returns an array, or .id =...
if it returns simply an object.对于这种情况,您可以使用.map(val => val.id =...)
如果它返回一个数组,或者.id =...
如果它只返回一个 object。 To ensure not modifying the original object, it is better to deep copy your object first.为确保不修改原始 object,最好先深拷贝您的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.