I am very new to typescript so I do not know what exactly the error means or how to fix it.
This is my code
app.put('/compareSpread' , async (req , res) => {
const { roundedSpreadPercentage , cropId} = req.body
const crop = await CropInfo.find({entity: cropId})
const diseaseSpreadOne = crop.diseaseSpreadOne
})
The error appears on the "const diseaseSpreadOne = crop.diseaseSpreadOne line.
Below is what the object from the database looks like:
[
{
_id: new ObjectId("6349fbcde56e8b6b9dc94266"),
entity: '64287197',
diseaseName: 'Fungi',
probability: 74.3,
diseaseCause: null,
diseaseDescription: 'Fungi take energy from the plants on which they live, causing damage to the plant. Fungal infections are responsible for approximately two-thirds of infectious plant diseases and cause wilting, molding, rusts, scabs, rotted tissue, and other problems.',
biologicalTreatment: [
'If possible remove and destroy the infected parts of the plant (burn it, toss it into the garbage, or bury it deeply). Do not compost.',
'Apply ecological products for plant protection (e.g. neem oil, baking soda, soap).'
],
chemicalTreatment: [ 'If necessary, apply a fungicide.' ],
prevention: [
'Use resistant species and cultivars as well as healthy, certified seeds and seedlings.',
'Avoid overwatering. Ensure having good soil drainage.',
'Improve the air circulation around the plant.',
'Avoid prolonged wetting of the leaves - avoid overhead irrigation.',
'Rotate crops. Avoid planting sensitive crops in infested soil.',
'Disinfect tools and hands to avoid disease transmission.'
],
image: 'https://plant.id/media/images/60e642b6cf4145739bde0c0947fcd933.jpg',
plantTrue: 'true',
is_healthy: 'false',
healthyBoolean: false,
dateTime: '2022-10-15',
diseaseSpreadOne: 19.1,
diseaseSpreadTwo: 19.1,
__v: 0
}
]
The above data is what is returned from the database but I still do not understand what the error is.
CodePudding user response:
You can use the as keyword to assert that the return value is of an expected type
type MyType = {
entity: string
diseaseName: string
...
diseaseSpreadOne: number
}
app.put('/compareSpread' , async (req , res) => {
const { roundedSpreadPercentage , cropId} = req.body
const crop = await CropInfo.find({entity: cropId}) as MyType
const diseaseSpreadOne = crop.diseaseSpreadOne
})
CodePudding user response:
the error says "property does not exist on type any[]". The .find
method returns an array, which wont have this property. This code will work:
pop the element out of the array
infer the type as any or any custom type containing the property
const crop = await CropInfo.find({entity: cropId}) // or your custom type const obj = crop.pop() as any; const diseaseSpreadOne = obj.diseaseSpreadOne; Also you can have in the model repository your own types and it will infer the type accordingly when querying from the database.