I am using GraphQL and Mongoose, and there is a subdocument within the document "Events" that will have an array of "tasks". I want users to be able to perform standard CRUD operations on these tasks and events, and I have been able to implement create and read operations just fine, but struggling over updates. Because the parent document is itself within an array of other events for a given user, I have been using Event.findOneAndUpdate
to access the event whose tasks we want to edit, say to change the name. But how can I access the particular task from among the array of other tasks to update, without setting them all?
Event model:
const {Schema, model} = require("mongoose");
const taskSchema = require("./Task");
const dateFormat = require("../utils/dateFormat");
const eventSchema = new Schema(
{
eventName: {
type: String,
required: true
},
eventType: {
type: String,
required: true
},
eventDate: {
required: true,
type: Date,
default: Date.now,
get: dueDate => dateFormat(dueDate)
},
duration: {
type: Number,
min: 0.25,
max: 12,
required: false
},
location: {
type: String,
required: false
},
username: {
type: String,
required: true
},
tasks: [taskSchema]
},
{
toJSON: {
getters: true
}
}
);
eventSchema.virtual("taskCount").get(function() {
return this.tasks.length;
});
const Event = model("Event", eventSchema);
module.exports = Event;
(unfinished) Edit Task resolver:
editTask: async (parent, {eventID, taskID, name, dueDate, completed}) => {
const updatedEvent = await Event.findOneAndUpdate(
{tasks._id: taskID},
{
$set: {
tasks.$.name: name,
}
}
);
};
return updatedEvent;
}
The Mutation as it appears in my Apollo sandbox:
export const EDIT_TASK = gql`
mutation editTask($eventID: ID!, $taskID: ID!, $name: String, $dueDate: String, $completed: String){
editTask(eventID: $eventID, taskID: $taskID, name: $name, dueDate: $dueDate, completed: $completed) {
_id
eventName
tasks {
_id
name
dueDate
completed
}
}
}
`
I would love to figure out how I can specifically select the task I want to update, and I'm not sure if I'm on the right track right now. Thanks!