Dynamically create collection with Mongoose

前端 未结 6 1511
我寻月下人不归
我寻月下人不归 2020-12-17 08:55

I want to give users the ability to create collections in my Node app. I have really only seen example of hard coding in collections with mongoose. Anyone know if its poss

6条回答
  •  醉话见心
    2020-12-17 09:28

    I believe that this is a terrible idea to implement, but a question deserves an answer. You need to define a schema with a dynamic name that allows information of 'Any' type in it. A function to do this may be a little similar to this function:

    var establishedModels = {};
    function createModelForName(name) {
        if (!(name in establishedModels)) {
            var Any = new Schema({ any: Schema.Types.Mixed });
            establishedModels[name] = mongoose.model(name, Any);
        }
        return establishedModels[name];
    }
    

    Now you can create models that allow information without any kind of restriction, including the name. I'm going to assume an object defined like this, {name: 'hello', content: {x: 1}}, which is provided by the 'user'. To save this, I can run the following code:

    var stuff = {name: 'hello', content: {x: 1}}; // Define info.
    var Model = createModelForName(name); // Create the model.
    var model = Model(stuff.content); // Create a model instance.
    model.save(function (err) { // Save
        if (err) {
            console.log(err);
        }
    });
    

    Queries are very similar, fetch the model and then do a query:

    var stuff = {name: 'hello', query: {x: {'$gt': 0}}}; // Define info.
    var Model = createModelForName(name); // Create the model.
    model.find(stuff.query, function (err, entries) {
        // Do something with the matched entries.
    });
    

    You will have to implement code to protect your queries. You don't want the user to blow up your db.

提交回复
热议问题