如何动态创建猫鼬模式?

How to create mongoose schema dynamically?

我有一个应用程序可以在 node.js 上使用 MongoDB 和 mongoose。我的应用程序只是 sends/deletes/edits 形成数据,为此,我有这样的猫鼬模型:

var mongoose = require('mongoose');

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

这很好用!

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

我看到建议使用 strict: falseSchema.Types.Mixed。但是,我无法弄清楚...... 我尝试过的:

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

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

有什么建议吗?提前致谢!

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

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:

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

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