'how to convert the POST data of different format to the declared schema type in nodejs?
I'm working on a nodejs project where I get data in a format that is similar to the final schema that I have to save, except for one property called location.
i get data in this format:
"location": [
{
"lat": 8.174450,
"long":77.432159
}
],
"job_description":"hththththty",
"email":"[email protected]",
"hireType":"Both",
Note: location comes as an array of objects of lat and long.
The final schema looks like:
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
default: [0, 0],
},
},
hireType: {
type: String,
enum: ['Half day', 'Full day', 'Both'],
default: ""
},
Now I have to save the lat and long(which comes in an array of objects) in the coordinates array inside the location property.
Except for this one property, all the other data format is similar to my schema.
After joi-validating the data I currently use the below code to save:
const { error, value } = validator.validate(req.body,{ abortEarly: false });
const service = new ServiceProvider();
service.name =value.name;
service.mobile =value.mobile;
service.email=value.email;
service.address=value.address;
service.locationAddress=value.locationAddress;
service.remember_token=value.remember_token;
service.email_verified_at=value.email_verified_at;
service.password= value.password;
service.hireType=value.hireType;
service.services=value.services;
service.location.coordinates[0]=value.location[0]['lat'];
service.location.coordinates[1]=value.location[0]['long'];
await service.save()
is there any way to improve my code to be a more dynamic type?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
