简体   繁体   中英

Mongoose use a variable as model with function find():

Is it possible to use a variable instead of the name of the model with the function find() in mongoose? For example, if my site can show photo and video based on the last path of the url, that can be either /photo or /video , can I use the same function to query the database by using a variable as the name of the model like this?

const getContent = async (req, res) => {
    const model = req.url;
    const data = await model.find();
}

This could save a lot of time and code.

No, It's not possible, because type of model should be function not a string you can using if and else for implementation of your business logic like this:

const getContent = async (req, res) => {
  let data;
  if (req.url === "photo") {
    data = await photo.find();
  } else if (req.url === "video") {
    data = await video.find();
  }
};

You could first create a map out of your available Models, like

const Models = {
  photo : Photo,
  video : Video
};

And then use it in your controller like

const getContent = async (req, res) => {
    const model = Models[req.url];
    const data = await model.find();
    res.json(data);
}

Be aware, even if it looks like less code needed, there still needs to be appropiate error handling involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM