如何使用 nodejs 动态创建 Mongodb 模式 [英] How to create Mongodb schema dynamically using nodejs

查看:61
本文介绍了如何使用 nodejs 动态创建 Mongodb 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 Mongoose 模式、Node.js 和 Angular 在 mongodb 中动态创建表.

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

创建模式的基本方法是在 Node.js 中显式创建一个模型,如下所示:

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);

是否可以使用来自 Angular 前端的用户输入动态创建此架构?

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

推荐答案

当然有可能... - 建议使用 表示为服务器框架:

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

这篇关于如何使用 nodejs 动态创建 Mongodb 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆