0

I am new in MongoDb and NodeJS. I want to create collections of a table.

Here is my JSON response :-

{
    "_id": "5c85f83516f5ad7ef3e14",
    "companyName": "XYZ",
    "fullName": "ABC",
    "designation": "Software Engineer",
    "companyID": "14224",
}

Here I am getting an unique companyID for a particular companyName. I want to create as many collections as much there will be unique companyID. How can I achieve it by NodeJS , ExpressJS code ?

EDIT:- controller file.

module.exports.registerAdmin = (req, res, next) =>{ 
    var admin = new Admin();
    admin.companyName = req.body.companyName;
    admin.email = req.body.email;
    admin.password = req.body.password;
    admin.fullName = req.body.fullName;

//----creating hash token for email verification ------------
const secret = crypto.randomBytes(20);
const hash = crypto.createHmac('sha256', secret)
                   .update(secret + admin.email)
                   .digest('hex');

//comapny id generate
const reqq = crypto.createHash('md5').update(admin.companyName).digest('hex');
let valueNum = reqq.match(/\d/g).join("").toString().substring(0,6);

admin.companyID = valueNum;

    //saving users data to database
    admin.save((err, doc) =>{
        if(!err){
            res.send(doc);
                let coSchema = coName => {
                    return {
                        id: {type: String, index: true},
                        coName: {default: coName}
                    }
                }

                response.then((data) => {
                    let coSchema;
                    data.forEach((doc) => {
                        coSchema = coSchema(doc.companyID);
                        mongoose.model(doc.companyID, coSchema);
                    })
                }
        }
        else{
            if (err.code == 11000)
                    res.status(422).send(["Entered duplicate email address. Please check"]);
            else
            return next(err);
            }
    });
}

Model :=

var adminSchema = new mongoose.Schema({
    companyName : {
                type: String,
                required: "Company  name can't be empty.",
                required: false
                },  
    companyID:  {
                type: String,
                unique: true
                },          
    email :     {
                type: String,
                required: "Email can't be empty.",
                unique: true
                },
    password:   {
                type: String,
                required: "First name can't be empty."
                },
    fullName: {
                type: String,
                required: "First name can't be empty."
                },
designation :   {
                type: String,
                required: "Designation can't be empty."
                }           
});

mongoose.model('Admin', adminSchema);
NoobCoder
  • 493
  • 8
  • 25
  • _I want to create as many collections as there will be unique companyID_ you mean documents right ? not collection ? – Muhammad Usman Mar 11 '19 at 07:03
  • @GeorgeBailey No , not documents. I need to create collections. Within a DBS I need to create collections with `companyIDs` values ie; 14224 , 34344 ,54454 etc – NoobCoder Mar 11 '19 at 07:04
  • So you are working on a multi tenent application? with multiple collection for each client? check this https://stackoverflow.com/questions/15306916/dynamically-create-collection-with-mongoose – AZ_ Mar 11 '19 at 07:05
  • @AZ_ Yes. You are correct – NoobCoder Mar 11 '19 at 07:07
  • @AZ_ It didn't helped much . – NoobCoder Mar 11 '19 at 08:37

1 Answers1

0

define your company Schema inside a function which accepts the com name and return the schema object.

say response is the array of documents read from db, parse through each and create a collection as per company Name, ensure company name is defined unique i your response schema

let coSchema = coName => {
 return {
  id: {type: String, index: true}, //need to have index created on some unique value to get the schema created without documents.
  coName: {default: coName}
  //add your feilds
 }
}

response.then((data) => {
 let coSchema;
 data.forEach((doc) => {
  coSchema = coSchema(doc.companyID);
  mongoose.model(doc.companyID, coSchema);
 })
})
Handle your promises accordingly.
AZ_
  • 3,094
  • 1
  • 9
  • 19
  • Should i try this in controller or model ? As I need to pass the function when registration happens in controller save function I guess. – NoobCoder Mar 11 '19 at 10:13
  • depends if you need company name also in your schema if not you can create a default model for all tenants. – AZ_ Mar 11 '19 at 10:15
  • I have added the controller in my EDIT. Am I doing it right ? When I am passing `let coSchema = admin.companyName` showing error `Unexpected token .` – NoobCoder Mar 11 '19 at 10:27
  • I want empty collection at first. As I am use those collections with different schemas – NoobCoder Mar 11 '19 at 10:47
  • my code is just an example to achieve what you are trying to do, you cant simply copy paste it in your already developed code. – AZ_ Mar 11 '19 at 10:52
  • where you have added let coSchema = admin.companyName ? – AZ_ Mar 11 '19 at 10:54
  • Ok got it. I am adding model file also in EDIT plz have a look – NoobCoder Mar 11 '19 at 11:50
  • Here you said "response is the array of documents read from db" , but it is being created with the same API. whatever the `companyID` in the response, will be the new collection with unique ID only. Not similar – NoobCoder Mar 11 '19 at 12:28
  • ohh ok, I thought its something like an inner join, if you are getting it from some api, you don't need to use forEach and all. – AZ_ Mar 11 '19 at 12:47
  • The response will going to be created in with this api only where I am creating the function. – NoobCoder Mar 11 '19 at 13:11