【问题标题】: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

【问题讨论】:

    标签: node.js mongodb typescript mongoose mongoose-schema


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多