How to access data from dynamically created collection using Node Express and MongoDB

Issue

Here is the code. I am creating dynamically collection but cannot access the created collection to access data. Any help would be appreciated.

exports.dynamicCollection = async (req, res) => {
  try {
    var stuff = {
      any: req.body.any,
    };
    var Model = createModelForName(req.body.name); // Create the model.
    var model = Model(stuff); // Create a model instance.
    model.save(function (err) {
      if (err) {
        return res.status(500).json(err);
      }
      return res.status(200).json('success');
    });
  } catch (err) {
    return res.json(err);
  }
};
var establishedModels = {};
function createModelForName(name) {
  if (!(name in establishedModels)) {
    var Any = new Schema({
      any: {},
    });
    establishedModels[name] = mongoose.model(name, Any);
  }
  return establishedModels[name];
}

Solution

Well i got the answer how to access dynamically created collections by R&D. Below is the code to access that,

const document = await createModelForName("test").find();

In place of test you can add name of the collection and you will get the data.

Answered By – Umar Akmal

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published