Related to Nextjs but not more to mongodb in nextjs and typescript, here is my question:
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
Question regarding mongodb and typescript. using lean() funciton i have to do this big mess of typescript transformations of if ect. Is there a more straighforward way to get the day withoug this typescript mess, should i not use lean(). here a next js action example below:
'use server';
import {
CountryDocument,
CategoryScore,
Metric,
} from '@/types/CountryDocument';
import connectDB from '@/lib/connectDB';
import Country from '@/models/Country';
export async function fetchCountryData(
countryName: string
): Promise<CountryDocument> {
await connectDB();
try {
const country = await Country.findOne({
name: {
$regex: `^${countryName}$`,
$options: 'i', // Case-insensitive match
},
}).lean<CountryDocument>(); // Explicitly define the expected type
if (!country) {
throw new Error('Country not found');
}
// Transform MongoDB ObjectId fields to strings
const transformedCountry: CountryDocument = {
...country,
_id: country._id?.toString(), // Convert _id to string
categoryScores: country.categoryScores.map((category: CategoryScore) => ({
...category,
_id: category._id?.toString(), // Convert category _id to string
categoryEmoji: category.categoryEmoji || '', // Default emoji to empty string
metrics: category.metrics.map((metric: Metric) => ({
...metric,
_id: metric._id?.toString(), // Convert metric _id to string
})),
})),
};
console.log('Transformed Data:', transformedCountry.categoryScores);
return transformedCountry;
} catch (error) {
console.error('Error fetching country:', error);
throw new Error('Error fetching country');
}
}