我正在做一个涉及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的正确类型查找方法