【问题标题】:How to create mongoose schema dynamically?如何动态创建猫鼬模式?
【发布时间】:2015-03-25 19:56:09
【问题描述】:

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

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 必须正确构建。 我的问题是:如何将变量值(动态创建的表单数据名称及其文本)添加到猫鼬模式?

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

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

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

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 该代码有效并发布默认表单数据:user_id、LogTime 和 feeds 数组及其对象,但是当我将另一个属性添加到 feeds 数组中时,例如:customText,它不会更新该 customText,而是更新其余部分。 ..我会搜索我仍然做错的地方..无论如何谢谢!
    • 如果您想向feeds 添加任意属性,则还需要在该嵌入式架构上设置该选项。查看更新的答案。
    • YES!!!:) 第二个选项正是我数小时以来一直在尝试做的事情!非常感谢!
    • @JohnnyHK 你能帮忙告诉我如何编写一个模式来将 json 数据插入到这样的 appFormSchema 中吗?我的意思是我正在将如此复杂的 json 从我的应用程序发送到服务器,其中 rest api 使用我预定义的模型模式来插入数据。事情是在插入时我在 feeds 数组中有不同数量的 json 对象,那么如何将它们映射到 db 中?
    猜你喜欢
    • 2012-04-22
    • 2014-12-04
    • 2014-06-01
    • 2021-05-10
    • 1970-01-01
    • 2021-09-22
    • 2018-08-27
    • 2015-10-14
    相关资源
    最近更新 更多