如何从猫鼬中获取类型化的对象
Posted
技术标签:
【中文标题】如何从猫鼬中获取类型化的对象【英文标题】:How to get typed object from mongoose 【发布时间】:2021-01-03 20:24:25 【问题描述】:我在 typescript 中有一个 nodejs 应用程序,我最近开始使用 mongoose 来查询 mongo db,但我正在努力寻找一种从 findById 方法获取类型化对象的方法。有没有办法通过某种方式从该方法中获取类型化对象?
import * as mongoose from 'mongoose';
export const LinksCacheSchema = new Schema(
ts:
type: Date,
default: Date.now()
,
imdbId: String,
parentLink: String,
playableLink: String,
status: String,
title: String,
size: Number,
contentType: String,
, collection: 'links_cache' );
export const LinksCacheList = mongoose.model('LinksCache', LinksCacheSchema);
const linkInfo = await LinksCacheList.findById(documentId); //this is the one returning type of any instead of LinksCacheSchema or any specific type
【问题讨论】:
【参考方案1】:您可以为该架构创建和导出接口:
import mongoose, Schema, Document, Model from 'mongoose';
export interface ILinksCacheSchema extends Document
ts: Date,
imdbId: string,
parentLink: string,
playableLink: string,
status: string,
title: string,
size: number,
contentType: string,
const LinksCacheSchema = new Schema(
ts:
type: Date,
default: Date.now()
,
imdbId: String,
parentLink: String,
playableLink: String,
status: String,
title: String,
size: Number,
contentType: String,
, collection: 'links_cache' );
export const LinksCacheList: Model<ILinksCacheSchema> = mongoose.model('LinksCache', LinksCacheSchema);
// in your app logic
const linkInfo = await LinksCacheList.findById(documentId);
两次创建架构可能会有点乏味,所以我建议你看看这个:
https://www.npmjs.com/package/ts-mongoose
【讨论】:
以上是关于如何从猫鼬中获取类型化的对象的主要内容,如果未能解决你的问题,请参考以下文章