looking for some solutions? You are welcome.

SOLVED: Create collections in mongdb from nodejs

NoobCoder:

I am passing schema from model to controller. I want to create a collections in MongoDB as from pa particular JSON response upon post.

model:-

const mongoose = require ('mongoose');
const bcryptt = require('bcryptjs');
const crypto = require('crypto');

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."
                }
});

mongoose.model('Admin', adminSchema);

So here I am using companyName to create compantID in controller:-

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;


//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;
console.log(valueNum);

    admin.save((err, doc) =>{
        if(!err){
            res.send(doc);
            //todo something here to generate collection from valueNum
        }
        else{
            if (err.code == 11000)
                    res.status(422).send(["Entered duplicate email address. Please check"]);
            else
            return next(err);
            }
    });
}

So I am getting companyID in valueNum. Upon admin.save I want to pass valueNum in some code to create new collection of whatever unique valueNum will be in the existing DB. If collection with a particular valueNum already existing in the DB , then skip.How can I achieve this ??



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent