Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Schema, model } from "mongoose";
- const eventSchema = new Schema({
- callTimes: { type: Array, of: Date, required: true },
- eventDate: { type: Date, required: true },
- employeeResponses: [
- {
- _id: {
- type: Schema.Types.ObjectId,
- ref: "User",
- required: true,
- },
- response: { type: String, required: true },
- notes: String,
- },
- ],
- scheduledEmployees: [
- {
- _id: { type: Schema.Types.ObjectId, ref: "User" },
- },
- ],
- });
- export default model("Event", eventSchema);
- [
- {
- "_id": "5d5daaafcf11d95c0a75a023",
- "callTimes": [
- "2019-08-21T10:30:41-07:00",
- "2019-08-21T11:00:41-07:00",
- "2019-08-21T11:30:41-07:00"
- ],
- "eventDate": "2019-08-20T02:30:36.000Z",
- "employeeResponses": [],
- "scheduledEmployees": []
- },
- {
- "_id": "5d5b5ee857a6d20abf49db19",
- "callTimes": [
- "2019-08-19T17:15:43-07:00",
- "2019-08-19T17:45:43-07:00",
- "2019-08-19T18:15:43-07:00",
- "2019-08-19T19:00:43-07:00"
- ],
- "eventDate": "2019-08-21T02:30:36.000Z",
- "employeeResponses": [
- {
- "_id": "5d5b5e952871780ef474807b",
- "response": "Available to work.",
- "notes": "I can work all day."
- },
- {
- "_id": "5d5b5e952871780ef474807c",
- "response": "Not available to work.",
- "notes": "I have school during that time."
- }
- ],
- "scheduledEmployees": []
- }
- ...etc
- ]
- const updateFormAp = async (req, res) => {
- try {
- const { _id, responses, notes } = req.body;
- if (!_id || !responses) throw "Missing required update event parameters. You must include an event id and response.";
- const formExists = await Form.findOne({ _id });
- if (!formExists) throw "Unable to locate that event form.";
- // iterate over responses and update the Events accordingly...
- await Event.bulkWrite(
- responses.map(response => {
- try {
- const { id: eventId, value, updateEvent } = response;
- const { id: userId } = req.session.user;
- // if the employee response exists...
- const filter = updateEvent
- ? {
- // set the filter to event id + employee id
- _id: eventId,
- "employeeResponses._id": userId,
- }
- : {
- // else set the filter to event id only
- _id: eventId,
- };
- // if the employee response exists...
- const update = updateEvent
- ? {
- // update the sub document in place
- $set: {
- "employeeResponses.$.response": value,
- "employeeResponses.$.notes": notes,
- },
- }
- : {
- // else add a new sub document
- $push: {
- employeeResponses: {
- _id: userId,
- response: value,
- notes,
- },
- },
- };
- return {
- updateOne: {
- filter,
- update,
- },
- };
- } catch (error) {
- throw error;
- }
- }),
- );
- res
- .status(201)
- .json({ message: "Successfully added your responses to the A/P form!" });
- } catch (err) {
- res
- .status(400)
- .json({ error: err.toString() });
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement