【问题标题】:Why mongoose Model object returned got a _id property, but id works as well in Typescript?为什么返回的 mongoose 模型对象具有 _id 属性,但 id 在 Typescript 中也能正常工作?
【发布时间】:2021-07-25 02:11:55
【问题描述】:

我使用 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

正如您所注意到的,我在第一个 console.log 中将 _id 作为属性,但是当我在 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

【问题讨论】:

  • 也许有一些别名或打字稿功能?

标签: typescript mongoose


【解决方案1】:

这是猫鼬的一个特点。所以它不会发生,因为你使用的是 TypeScript,如果你用 JavaScript 做它也会发生。

默认情况下,Mongoose 会为您的每个模式分配一个 id 虚拟 getter 它将文档的 _id 字段转换为字符串,或者在 ObjectIds 的情况,它的 hexString。

【讨论】:

    【解决方案2】:

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

    更多信息here

    【讨论】:

      猜你喜欢
      • 2017-10-06
      • 2011-05-03
      • 2013-01-17
      • 2021-12-06
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      相关资源
      最近更新 更多