Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Mongodb schema dynamically using nodejs

I'm wondering if it's possible to create a table dynamically in mongodb using a Mongoose schema, Node.js and Angular for example.

The basic way to make a schema is to create a model explicitly in Node.js like this:

import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const postSchema = new Schema({
    title: { type: 'String', required: true },
    content: { type: 'String', required: true },
    slug: { type: 'String', required: true }
});

let Post = mongoose.model('Post', postSchema);

Is it possible to create this schema dynamically by using the user input from an Angular frontend?

like image 881
toto totto Avatar asked May 06 '19 12:05

toto totto


People also ask

How do I create a schema in MongoDB using node JS?

import mongoose from 'mongoose'; const Schema = mongoose. Schema; const postSchema = new Schema({ title: { type: 'String', required: true }, content: { type: 'String', required: true }, slug: { type: 'String', required: true } }); let Post = mongoose. model('Post', postSchema);

How do you make a dynamic model mongoose?

var mongoose = require('mongoose'); var Schema = mongoose. Schema; var feedSchema = new Schema({strict:false}); module. exports = mongoose. model('appForm', feedSchema);

What is dynamic schema in MongoDB?

A dynamic schema supports fluent polymorphism. Embedded Data Model: MongoDB uses an embedded data model. In other words, we can define a document as a key/value pair in another document. Use of Index: We can define an index on any attributes of a MongoDB records that increase the speed of data fetching.

What is findById in MongoDB?

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.


1 Answers

Sure it's possible... - suggesting using express as server framework:

import mongoose from 'mongoose';
import { Router } from 'express';
const router = Router();

router.post('/newModel/', createNewModel);

function createNewModel(req, res, next) {
  const Schema = mongoose.Schema;
  // while req.body.model contains your model definition
  mongoose.model(req.body.modelName, new Schema(req.body.model));
  res.send('Created new model.');
}

...but please be careful! Opening a way for users to modify your database so easily is usually not a good idea.

Update: The format is exactly the same as the one you want to have in the paranthesis:

{
  "title": { "type": "String", "required": "true" },
  "content": { "type": "String", "required": "true" },
  "slug": { "type": "String", "required": "true" }
}
like image 190
noChance Avatar answered Sep 28 '22 10:09

noChance