【问题标题】:How to generate simple schema from database in meteor如何从流星中的数据库生成简单模式
【发布时间】:2015-05-09 06:46:28
【问题描述】:

我们如何从流星应用程序中的数据库生成模式。 我想从每个数据库条目生成多个模式。

使用的 DB 是 Mongo DB。

此架构稍后将用于生成表单。

我正在使用 autoform 生成表单。

[1:http://autoform.meteor.com]

【问题讨论】:

标签: json mongodb meteor database-schema meteor-autoform


【解决方案1】:

我编写了一个小脚本,您可以在 mongo 中运行它来对现有(平面)集合进行逆向工程。

/*
**  SimpleSchema definition generator  
**  
**  This will reverse engineer a flat collection
**  only at this point. If you improve this,
**  please share: {"email-left": "timstew", "at":"@", "email-right": "gmail.com"} 
**                              
*/
var schemaName = "publisherSchema"; // Name you want to give to your simple schema
var collectionName = "publishers"; // mongodb collection name (not including 'db.')
var sampleID = "54c00f0d2b21500370a2e4c4"; // _id of a good representative document

// OK, that's all the info we need - Let's get started!
var message = eval("db." + collectionName + ".findOne({_id:\"" + sampleID +"\"})");
var count = 0;
// Hack because I can't figure out how to find out how many fields are in 
var numKeys = 0;
for(var key in message) {numKeys += 1}

var index = 0;
for (var key in message) {
    if (index == 0) {
        print(schemaName + " = new SimpleSchema({");
        }
    print("\t" + key + ": {");
    print("\t\ttype: " + toProper(eval("typeof db." + collectionName + ".findOne({_id:\"" + sampleID + "\"})." + key)) + ",");
    print("\t\tlabel: \"" +  toProper(key) + "\"");

    if (index == numKeys-1) {
        print("\t\t}");
        print("\t})");
    } else {
        print("\t\t},");
    }
    index += 1;
}

function toProper(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

【讨论】:

    【解决方案2】:
    1. MongoDB 是一个文档数据库,不需要架构。您只需declare collections in Meteor
    2. 如果您想严格控制文档结构,请查看https://github.com/aldeed/meteor-collection2 (meteor add aldeed:collection2)

    我最近解释了 Meteor 集合和模式 here

    如果您想从集合中读取架构,您可以通过collectionName.simpleSchema() 简单地访问它。出于您的目的,您可以采用此架构并将其转换为您想要的结构(或排除某些配置的字段)。

    【讨论】:

    • 我要显示该对象的所有项目,你能举个例子吗?
    • 你是说我只需要展示收藏吗?
    • 啊明白了。扩展答案。最后一段应该为您指明正确的方向。
    • 所以如果我有多个架构,我应该将其保存在同一个集合中还是创建不同的集合?
    • 如果您正在谈论将关系模式转换为文档模式,这实际上取决于您要对数据做什么。基于文档的数据库背后的想法有很大不同。在关系数据库中,我个人倾向于传播我的对象,而在基于文档的数据库中,我只为我的根对象创建集合。特别是关系通常不存储在单独的集合中,而是作为字段 (1..1) 或值列表 (1..n, n..m)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2014-08-20
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多