Snoopy
Snoopy

Reputation: 1357

Using findOneAndUpdate with varying field values

I am curious to know if there is a better way to go about updating field values. The field values I use sometimes will be there and sometimes will not be, depending on the type of post the user is creating:

Here is my code to bield out the fields that are to be added to the database

switch (req.body.postType) {
      case "text":
        postFields = {
          postType: "text",
          postBody: req.body.postBody
        };
        break;
      case "video":
        postFields = {
          postType: "video",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          video: {
            ...req.files["postVideo"][0],
            thumbnail: { ...req.files["postVideoThumbnail"][0] }
          }
        };
        break;
      case "photo":
        postFields = {
          postType: "photo",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          photo: {
            ...req.files["postPhoto"][0]
          }
        };
        break;
      case "document":
        postFields = {
          postType: "document",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          document: {
            ...req.files["postDocument"][0]
          }
        };
        break;
      default:
        return res.status(400).json({
          Error:
            "Incorrect postType sent to server. Must be: text, video, photo"
        });
    }

After I build this out I then use findOneAndUpdate as follows

 Feed.findOneAndUpdate(
              { school: req.user.school },
              {
                $push: {
                  posts: postFields
                }
              },
              { new: true }
            )

Is there a better way to create the field values?

Upvotes: 0

Views: 59

Answers (1)

Akrion
Akrion

Reputation: 18515

You could do something like this since you already are using ES6:

let { postType, postBody, postTitle } = req.body  // <-- de-structure
let postFields = {
    postType,
    postBody,
    postTitle,  // <-- no title for text?
    ...(type === 'video' ? { video: {...req.files["postVideo"][0], thumbnail: { ...req.files["postVideoThumbnail"][0]}}} : {}),
    ...(type === 'photo' ? { photo: { ...req.files["postPhoto"][0]}} : {}),
    ...(type === 'document' ? { document: {...req.files["postDocument"][0]}} : {}),
}

if text has no title then just use the same approach as the video etc where you use the ternary operator and if type is text just add the title via spreading an object with the title ...

Basically the idea is to use spread with a ternary operator to conditionally decorate an object with properties.

Upvotes: 1

Related Questions