首页 > 解决方案 > 为什么返回的 mongoose 模型对象具有 _id 属性,但 id 在 Typescript 中也能正常工作?

问题描述

我正在使用 Typescript 来获取对象

const query = Workflow.where({ _id: id });
const workflow = await query.findOne().exec();
console.log(workflow); // <-- (1) this console.log()
console.log(workflow.id); // <-- (2) this console.log()
return workflow;

然后我得到:

{
  _id: 608e7fb7ee267e23fff1da65,
  title: 'WorkFlow 14',
  description: 'Este es un nuevo workflow',
  date: 2021-05-02T10:32:23.423Z,
  __v: 0
}
608e7fb7ee267e23fff1da65

正如您所注意到的,我_id在第一个 console.log 中获得了属性,但是当我在 console.log 中workflow.id得到结果时。

我的架构

import mongoose from 'mongoose';

const WorkflowSchema = new mongoose.Schema({
  title: { type: String, required: true },
  description: { type: String, required: false },
  date: { type: Date, default: Date.now },
});

export default mongoose.model('Workflow', WorkflowSchema);

这只发生在 id 属性上。

为什么它起作用了?我预计会出现错误,或者undefined至少会出现错误。

标签: typescriptmongoose

解决方案


id是字符串版本,_id默认情况下,此 getter 存在于所有文档中。

更多信息在这里


推荐阅读