如何使用Node.js动态创建MongoDB模式

5
我在想是否可以使用Mongoose模式、Node.js和Angular动态创建MongoDB中的表格。
创建模式的基本方法是在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);

这个 schema 可以通过使用 Angular 前端的用户输入动态创建吗?

1个回答

5
当然可以……建议使用express作为服务器框架:express
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.');
}

但请小心!让用户如此轻易地修改您的数据库通常不是一个好主意。

更新:格式与括号中所需格式完全相同:

{
  "title": { "type": "String", "required": "true" },
  "content": { "type": "String", "required": "true" },
  "slug": { "type": "String", "required": "true" }
}

感谢@noChance的回答,但是你能否提及一下Angular发送的JSON格式的形式,例如在req.Model中? - toto totto
我试着用Postman发送以下内容: { "ModelName":"测试", "ModelContent":{ "title": "{ type: 'String', required: true }", "content": "{ type: 'String', required: true }" } } 但是它给了我一个错误: TypeError: 在title处未定义类型 { type: 'String', required: true } - toto totto
你的 JSON 对象无效,我尝试使用 Postman 发送它时出现了语法错误,请帮忙看一下吗? - toto totto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接