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

Time:09-06

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];
}

CodePudding user response:

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.

  • Related