Ok that question doesn't sound very clear. I will try to explain. I have a collection of F1 drivers that contains an array field to store the points earned from each race. I use a web form to submit the full result of a given race that contains the race_id, race_name, and a positions array that contains the driver_id and points earned as an object for each driver. I now need to update each driver in the collection with their result from this race by matching the driver id with the id in the object array. Ultimately; I will also need to update the total_points for each driver, but that can wait for now.
// The handler for my web form
function handleRaceResultSubmit(e) {
e.preventDefault();
let positions = [{id: null, points: 25}, {id: null, points: 18},{id: null, points: 15},{id: null, points: 12},{id: null, points: 10},
{id: null, points: 8},{id: null, points: 6},{id: null, points: 4},{id: null, points: 2},{id: null, points: 1},
{id: null, points: 0},{id: null, points: 0},{id: null, points: 0},{id: null, points: 0},{id: null, points: 0},
{id: null, points: 0},{id: null, points: 0},{id: null, points: 0},{id: null, points: 0},{id: null, points: 0},];
const eventID = parseInt(document.querySelector('#event-select').value);
const eventName = document.querySelector('#event-select').textContent;
const selectGroup = document.querySelectorAll('.select-group');
selectGroup.forEach((driver, index) => {
positions[index].id = parseInt(driver.value);
})
const raceResult = {
event_id: eventID,
event_name: eventName,
result: positions
}
updateDriverResults(raceResult);
}
// Post result to the endpoint
const updateDriverResults = async (data) => {
fetch('driver-points',
{
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
}).then(res => {return res.json()})
.then(data => console.log(data))
.catch(error => console.log(error));
}
//My endpoint and Mongoose query
app.post('/driver-points', express.json(), (req, res) => {
Drivers.updateMany({
'id': { $in: [ req.body.result.id ] },
},
{
$push: {'results': {
'event_id': req.body.event_id,
'event_name': req.body.event_name,
'points': req.body.result.points
}}
})
.then((result) => {
res.send(result);
})
.catch((error) => {
console.log(error);
})
})
// The model
import { mongoose } from "mongoose";
const Schema = mongoose.Schema;
const driversSchema = new Schema({
id: Number,
driver_name: String,
totla_points: Number,
results: Array
});
const Drivers = mongoose.model('driver', driversSchema);
export { Drivers };