Tuesday, 19 May 2020

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are different. so everytime you are creating a new model class for the mongoose object. so this post will help you to create a mongoose object with dynamic collection name. so let me show you how to create dynamic schema in mongodb.

mongodb,how to create dynamic schema in mongodb,dynamic schema,create a schema in mongodb,create new schema in mongodb,projects in mongodb,create schema in mongodb shell,how to create schema in mongodb,how to create a schema in mongodb,create database schema in mongodb,create collection schema in mongodb,how to create database schema in mongodb,create collection with schema in mongodb,how to create collection schema in mongodb,how to create schema in mongodb using node.js,mongodb schema


/* global mongoose */
var moment = require('moment');
let kindleModels = {};

/**
 * @author Wantcode.in
 * Kindle model is like store of all kind of mongo Schema
 * You don't need to create every time new schema for the mongolog
 * It's purpose is to create dynamic collection name
 */

const kindleSchema = new mongoose.Schema({
  url: String,
  method: String,
  request_type: String,
  request_data: Object,
  response_data: Object,
  userIp: String,
  fkey: {
    type: String,
    required: false,
    default: null
  },
  created_at: { type: Date, default: moment().tz(process.env.TZ).format() },
  updated_at: { type: Date, default: moment().tz(process.env.TZ).format() }
});

const kindleModel = collectionName => {
  if (!(collectionName in kindleModels)) {
    kindleModels[collectionName] = mongoose.model(
      collectionName,
      kindleSchema,
      collectionName
    );
  }
  return kindleModels[collectionName];
};

module.exports = kindleModel;

I have created a model called kindeModel this is dynamic mongoose model where you defined your collection name dynamically and call it where you want.

How to call it. import it where you want it to call.

const pageName = {
url : 'something',
fkey : 'something',
method: 'something',
user_agent:'something',
user_ip: '127.0.0.1',
request_data: {}
};      

const Kindle = kindleModel('api_logger'); // pass dynamic collection name here
const kitty = new Kindle(pageName); // pass object here
 
kitty
.saveAsync()
.then(result => {
  this.logId = result._id;
  resolve(result._id);
})
.catch(e => {
  reject(e);
});

Now your object is successfully saved in api_logger collection. Please like and share with your friends if you find this post awesome.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts