Search code examples
expresscollectionsmodelmongoose-schema

Changing the collection based on the request type


This controller accepts the form and updates the data.

export const createPost = async (req, res) => {
const { title, message, selectedFile, creator, tags } = req.body;

const newPostMessage = new OrangeModel ({ title, message, selectedFile, creator, tags })

try {
    await newPostMessage.save();

    res.status(201).json(newPostMessage );
} catch (err) {
    res.status(409).json({ message: err.message });
}

}

I want to change the collection type based on the request.

when the request is from the Grapes url, the model(or collection) should change to GrapeModel from OrangeModel. How to do this?


Solution

  • If you want a POST /Grapes to be behave differently from a POST /Oranges, you can attach your controller to both paths and evaluate the path inside your code.

    const createPost = async (req, res) => {
      let newPostMessage;
      if (req.path === "/Oranges") newPostMessage = new OrangeModel(...);
      else if (req.path === "/Grapes") newPostMessage = new GrapeModel(...);
      try {
        await newPostMessage.save();
      ...
    };
    app.post(["/Oranges", "/Grapes"], createPost);