typescript - 为什么返回的 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
至少会出现错误。
解决方案
id
是字符串版本,_id
默认情况下,此 getter 存在于所有文档中。
更多信息在这里。
推荐阅读
- swift - 如何始终添加到 NSCollectionView 的末尾?
- java - 比较两个 ArrayList
- node.js - Sequelize JSON 字段只更新一个字段
- reactjs - 如何使用 Firestore 中的对象数组更新字段中的特定对象?
- javascript - Sequelize - 不要在 BelongsToSetAssociationMixin 上自动保存
- excel - 自动删除 Excel 中的特定行
- django - AWS Elastic Beanstalk 为 Django 应用程序配置允许的主机
- python - Pandas Python:将多标头写入excel
- node.js - 无法在反应应用程序“无效或意外令牌”中导入图像
- javascript - 在循环中执行 fetch 语句 javascript async-await