How to create Mongodb schema dynamically using nodejs

孤街浪徒 提交于 2021-02-07 07:23:40

问题


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?


回答1:


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" }
}


来源:https://stackoverflow.com/questions/56004918/how-to-create-mongodb-schema-dynamically-using-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!