我正在做一个涉及MongoDB的打字项目,我面临着正确输入MongoDB的find方法的挑战.以下是我正在使用的代码片段:

import { ReitsType } from '@/app/api/types/reits';
import { NextRequest, NextResponse } from 'next/server';
import { db } from '../mongo';
import { ActionsType } from '../types/actions';

export async function GET(req: NextRequest) {
    console.log(req);
    const sortKey: keyof ReitsType | keyof ActionsType =
        'averageDy5YearsRanking';
    try {
        const collection = db.collection('reits');
        const documents = await collection
            .find<ReitsType | ActionsType>({
                averageDy5YearsRanking: { $gte: 5 }
            })
            .sort({ [sortKey]: 1 })
            .toArray();
        return NextResponse.json(documents);
    } catch (error) {
        console.error('Error while fetching data:', error);
        return NextResponse.error();
    }
}

问题是我无法为Find方法返回的文档定义正确的类型.ReitsType和AtionsType接口表示可能的类型,但看起来类型脚本无法正确识别所使用的类型.

我想了解如何正确地键入Find方法,以便TypeScrip识别返回的文档类型,并为我提供适当的代码支持,例如自动完成属性和识别可能的类型错误.

MongoDB的正确类型查找方法

推荐答案

// you have to add the type here 
const collection = db.collection<ReitsType>('reits');

然后,当你写下:

 const documents = await collection.find()

TypeScrip将自动推断documents的类型,并将自动完成.如果你写

const documents = await collection.find().sort(whileCursorHere)

点击CTRL + SPACE,您将看到选项

enter image description here

但如果您需要指定排序的键

 const documents = await collection.find().sort({key:1})

一旦您点击CTRL+SPACE,而光标在sort({whileCursorHere}),您可能会看到您类型的键,在您的示例MyData中,

interface MyData {
  name: string;
  age: number;
  adress: string;
}

您可能希望看到nameageaddress的自动完成,但您不想,因为这是Fort sort类型的方法

sort(sort: Sort, direction?: SortDirection | undefined): FindCursor<WithId<MyData>>

并且Sort的类型不排除泛型

export declare type Sort = string | Exclude<SortDirection, {
    $meta: string;
}> | string[] | {
    [key: string]: SortDirection;
} | Map<string, SortDirection> | [string, SortDirection][] | [string, SortDirection];

Node.js相关问答推荐

如何修复PayPal Node.js Webhook中Webhook签名验证失败?''

如何在node.js中以随机顺序调用函数并按顺序操作

为什么 mongoose 没有常规数组方法

Mongodb - 在数组数组中查找()

如何从mongoose 对象内嵌套的数组中提取数组元素?

表达 js 错误处理程序在第一个之后被忽略

express 和 mongoose 的新密码不正确

Fly.io 启动问题:无法从源获取图像或构建错误:构建错误:连接期间出错:发布...

MongoDB Aggregate - 如何使用前一阶段的值作为下一阶段的字段名称?

fastify:流过早关闭

在 `DataFrame` 上使用用户定义的可链接函数抽象出 Polars 表达式

如何从 github 编译第三方扩展?

通过 npm 导入 Sass

在Go中,编写非阻塞代码有意义吗?

如何将子集合添加到 Firestore 中的文档?

代理(如提琴手)可以与 Node.js 的 ClientRequest 一起使用吗

在 Node.js 中使用公钥加密数据

nodeJS - 如何使用 express 创建和读取会话

Node.js 与 .net 中的异步/等待

node --experimental-modules,请求的模块不提供名为的导出