如何动态创建猫鼬架构? [英] How to create mongoose schema dynamically?

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

问题描述

我有一个可在MongoDB和mongoose上的node.js上运行的应用程序.我的应用程序只是发送/删除/编辑表单数据,为此,我有这样的猫鼬模型:

I have an app that works on node.js with MongoDB and mongoose. My app simply sends/deletes/edits form data and for that, I have such mongoose model:

var mongoose = require('mongoose');

module.exports = mongoose.model('appForm', {
    User_id : {type: String},
    LogTime : {type: String},
    feeds : [   
    {
        Name: {type: String},
        Text : {type: String},
    }
    ]
});

那很好用!

现在,我想向表单添加一个功能,以便用户可以添加一个或多个要表单的字段,并在其中输入文本并发布. 在客户端上创建该动态功能没问题,但我知道必须正确构造mongoose.model. 我的问题是:如何将变量值(动态创建的表单数据名称及其文本)添加到猫鼬模式?

Now, I would like to add a function to the form so that the user can add a field(or fields) to form and enter a text in it and post it. Creating that dynamic functionality on the client side is no problem but I understand that my mongoose.model has to be correctly structured. My question is: how do I add that variable values(dynamically created form data name and its text) to mongoose schema?

我看到建议使用strict: falseSchema.Types.Mixed.但是,我不知道... 我尝试过的:

I see that using strict: false and Schema.Types.Mixed is advised. however, I can't figure out... What I have tried:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var feedSchema = new Schema({strict:false});

module.exports = mongoose.model('appForm', feedSchema);

有什么秘诀吗?预先感谢!

Any tips? Thanks in advance!

推荐答案

通过将strict: false选项作为第二个参数提供给Schema构造函数,将其应用于现有的模式定义:

Apply the strict: false option to your existing schema definition by supplying it as a second parameter to the Schema constructor:

var appFormSchema = new Schema({
    User_id : {type: String},
    LogTime : {type: String},
    feeds : [new Schema({
        Name: {type: String},
        Text : {type: String}
    }, {strict: false})
    ]
}, {strict: false});

module.exports = mongoose.model('appForm', appFormSchema);

如果要将feeds保留为完全无架构,则可以在其中使用Mixed:

If you want to leave feeds as fully schemaless, that's where you can used Mixed:

var appFormSchema = new Schema({
    User_id : {type: String},
    LogTime : {type: String},
    feeds : [Schema.Types.Mixed]
}, {strict: false});

module.exports = mongoose.model('appForm', appFormSchema);

这篇关于如何动态创建猫鼬架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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