Mongoose typings,id属性不可用

时间:2016-12-11 06:44:39

标签: node.js typescript mongoose typescript-typings

我将以下代码用于我的猫鼬TypeScript模型。

import mongoose = require('mongoose')

export interface PieceInterface extends mongoose.Document {
  date: Date
  summary: string
  source: string
  link: string
}

export const PieceSchema = new mongoose.Schema({
  date: { type: Date, default: new Date(), required: true },
  summary: { type: String, default: 'summary', required: true },
  source: { type: String, default: 'source', required: true },
  link: { type: String, default: '#', required: true }
})

export const Piece = mongoose.model<PieceInterface>('Piece', PieceSchema)

现在,当我使用Piece.find({}).then(x => {...})时,x符合预期Promise<PieceInterface[]>

然而,我无法获得

Piece.find({}).then(x => {
  console.log(x[0].id)
})

要正确编译,它总是告诉我error TS2339: Property 'id' does not exist on type 'PieceInterface'

PieceInterface延伸mongoose.Document后,我看了......

interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties

然后,

class MongooseDocument implements MongooseDocumentOptionals 

最后这个,

interface MongooseDocumentOptionals {
  id?: string;
}

在我看来,它应该有效。我可以使用MongooseDocumentModelProperties提供的变量,但不能使用MongooseDocumentOptionals

我遗失了什么?

参考文献:来自GitHub的mongoose.d.ts

Definition of document

Definition of MongooseDocument

Definition of MongooseDocumentOptionals

1 个答案:

答案 0 :(得分:0)

Mongo中ID的默认字段名称为_id而不是id,因此您应该执行以下操作:

Piece.find({}).then(x => {
  console.log(x[0]._id)
})