![](/img/trans.png)
[英]Returned Mongoose id different format than MongoDB shell results?
[英]Mongoose and TypeScript - returned _id is in strange format
從 TypeScript 查詢 MongoDB(通過 Mongoose)時有一些奇怪的響應。
有這兩個接口:
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[];
}
這些是 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);
使用model.find
返回owner
等於 13 的所有文檔
await ProjectModel.find({ owner: 13 })
.select("-__v")
.lean()
.exec();
這就是我在 Postman 中得到的響應。 不知道為什么_id
又回到了這種格式。 我試圖在界面中更改_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"
},
...
TypeScript 中的interface
未在運行時檢查 - 它僅在編譯時檢查。 因此,您不能簡單地直接在interface
中更改運行時結構。
對於這種情況,您可以使用.map(val => val.id =...)
如果它返回一個數組,或者.id =...
如果它只返回一個 object。 為確保不修改原始 object,最好先深拷貝您的 object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.