Dynamically create collection with Mongoose

前端 未结 6 1504
我寻月下人不归
我寻月下人不归 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:24

    This method works best for me , This example creates dynamic collection for each users , each collection will hold only corresponding users information (login details), first declare the function dynamicModel in separate file : example model.js

    /* model.js */
    'use strict';
    
    var mongoose = require('mongoose'),
      Schema = mongoose.Schema;
    
    
      function dynamicModel(suffix) {
          var addressSchema = new Schema(
              {
                   "name" : {type: String, default: '',trim: true},
                   "login_time" : {type: Date},
                   "location" : {type: String, default: '',trim: true},
              }
      );
    
         return mongoose.model('user_' + suffix, addressSchema);
    
      }
    
    module.exports = dynamicModel;
    

    In controller File example user.js,first function to create dynamic collection and second function to save data to a particular collection

    /* user.js */
    var  mongoose = require('mongoose'),
    
    function CreateModel(user_name){//function to create collection , user_name  argument contains collection name
    
      var Model  = require(path.resolve('./model.js'))(user_name);
    
    }
    
    function save_user_info(user_name,data){//function to save user info , data argument contains user info
         var UserModel  = mongoose.model(user_name) ;
         var usermodel  = UserModel(data);
                  usermodel.save(function (err) {
    
                   if (err) {
                      console.log(err);
                    } else {
                     console.log("\nSaved");
                    }
               });
    }
    

提交回复
热议问题