【发布时间】:2021-08-14 22:05:17
【问题描述】:
从 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"
},
...
【问题讨论】:
-
这能回答你的问题吗? nodejs mongodb object id to string
-
有点跑题了,但我对 TypeScript 和 Mongoose 的体验是我见过的最糟糕的事情。如果您可以在 TypeScript 中为您的数据库文档定义精确的数据模型,也许您想考虑使用关系数据库,因此像 Prisma ORM prisma.io 这样的东西可能会使您的 TypeScript 开发经验增加 100。
-
@Hugo 在接下来的几天里可能会同意你的体验。目前,我只是在玩这个组合,看看感觉如何。
标签: node.js typescript mongodb mongoose