admin管理员组文章数量:1394981
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?
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?
Share Improve this question edited May 13, 2019 at 7:40 noChance 5132 silver badges14 bronze badges asked May 6, 2019 at 12:09 toto tottototo totto 652 silver badges10 bronze badges 1- Possible duplicate of Creating dynamic schema using mongoose – Vikash_Singh Commented May 13, 2019 at 11:10
1 Answer
Reset to default 5Sure 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" }
}
本文标签: javascriptHow to create Mongodb schema dynamically using nodejsStack Overflow
版权声明:本文标题:javascript - How to create Mongodb schema dynamically using nodejs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744111193a2591298.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论