node.js 如何动态创建猫鼬模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28166463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create mongoose schema dynamically?
提问by Mar
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:
我有一个使用 MongoDB 和 mongoose 在 node.js 上运行的应用程序。我的应用程序只是发送/删除/编辑表单数据,为此,我有这样的猫鼬模型:
var mongoose = require('mongoose');
module.exports = mongoose.model('appForm', {
User_id : {type: String},
LogTime : {type: String},
feeds : [
{
Name: {type: String},
Text : {type: String},
}
]
});
and that works just fine!
这工作得很好!
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?
现在,我想向表单添加一个函数,以便用户可以向表单添加一个(或多个)字段并在其中输入文本并发布。在客户端创建动态功能没有问题,但我知道我的 mongoose.model 必须正确构建。我的问题是:如何将变量值(动态创建的表单数据名称及其文本)添加到猫鼬模式?
I see that using strict: falseand Schema.Types.Mixedis advised. however, I can't figure out...
What I have tried:
我看到使用strict: false并被Schema.Types.Mixed建议。但是,我无法弄清楚......我尝试过的:
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!
有小费吗?提前致谢!
回答by JohnnyHK
Apply the strict: falseoption to your existing schema definition by supplying it as a second parameter to the Schemaconstructor:
通过将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);
If you want to leave feedsas fully schemaless, that's where you can used Mixed:
如果你想保持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);

