根据我对文档和模型关系示例的阅读,我没有看到如何在 MongoDB 中保存一对多关系。我有以下模型:
1. Category
2. Post
Category 有很多 Posts 并且 Post 属于 Category
我使用的外键是“categoryId”
我使用以下脚本将示例数据插入 MongoDB:
create-categories.js:
var categories = [
{"title" : "Technology Matters", "description": "Blogs on latest technologies"},
{"title" : "Innovative Ideas", "description": "Innovative ideas on the next project"},
{"title" : "Comments on Hot Topics", "description": "My comments on the hot topics"}
];
module.exports = function(server) {
var dataSource = server.dataSources.mongoDatastore;
dataSource.automigrate('Category', function(err) {
if (err) throw err;
var Model = server.models.Category;
//create some sample data
var count = categories.length;
categories.forEach(function(category) {
Model.create(category, function(er, result) {
if (er) return;
console.log('Category created: ', result);
count--;
if (count == 0) {
console.log('Categories all created!');
dataSource.disconnect();
}
});
//could define a model scope here
});
});
};
create-posts.js:
var posts = [
{"title" : "Post 1 Title", "bodyText": "body text for blog post 1", "dateCreated": new Date(), "categoryId": 1},
{"title" : "Post 2 Title", "bodyText": "body text for blog post 2", "dateCreated": new Date(), "categoryId": 1},
{"title" : "Post 3 Title", "bodyText": "body text for blog post 3", "dateCreated": new Date(), "categoryId": 2},
{"title" : "Post 4 Title", "bodyText": "body text for blog post 4", "dateCreated": new Date(), "categoryId": 2},
{"title" : "Post 5 Title", "bodyText": "body text for blog post 5", "dateCreated": new Date(), "categoryId": 1},
{"title" : "Post 6 Title", "bodyText": "body text for blog post 6", "dateCreated": new Date(), "categoryId": 3},
{"title" : "Post 7 Title", "bodyText": "body text for blog post 7", "dateCreated": new Date(), "categoryId": 2},
{"title" : "Post 8 Title", "bodyText": "body text for blog post 8", "dateCreated": new Date(), "categoryId": 3},
{"title" : "Post 9 Title", "bodyText": "body text for blog post 9", "dateCreated": new Date(), "categoryId": 1},
{"title" : "Post 10 Title", "bodyText": "body text for blog post 10", "dateCreated": new Date(), "categoryId": 2}
];
module.exports = function(server) {
var dataSource = server.dataSources.mongoDatastore;
dataSource.automigrate('Post', function(err) {
if (err) throw err;
var Model = server.models.Post;
//create some sample data
var count = posts.length;
posts.forEach(function(post) {
Model.create(post, function(er, result) {
if (er) return;
console.log('Post created: ', result);
count--;
if (count == 0) {
console.log('Posts all created!');
dataSource.disconnect();
}
});
//could define a model scope here
});
});
};
请注意,上面每个帖子对象中伪造的“categoryId”只是临时的,我希望将 MongoDB 中的实际 categoryId 保存到每个帖子对象中。
我的问题是:当将每个帖子对象保存到 MongoDB 时,您将如何获得所有者的 ID(在本例中为 categoryId)。我的MongoDB中保存的类别如下,每个类别都有一个_id,是ObjectId类型。 Post集合中是否需要将类别ObjectId保存为外键?如果是,怎么做?
{
"_id" : ObjectId("55355f076ed9d911089ea0a7"),
"title" : "Technology Matters",
"description" : "Blogs on latest technologies"
}
{
"_id" : ObjectId("55355f076ed9d911089ea0a8"),
"title" : "Innovative Ideas",
"description" : "Innovative ideas on the next project"
}
{
"_id" : ObjectId("55355f076ed9d911089ea0a9"),
"title" : "Comments on Hot Topics",
"description" : "My comments on the hot topics"
}
最佳答案
托尼给你一些建议,
one < many而不是 one << many和 cardinality of one is not very high .您的问题的解决方案可能是,一个类别可以有多个帖子,但总共有多少个类别。在我看来,与帖子相比,一个(类别)的数量要少得多。
更好的存储数据的方法是,
创建一个名为 posts like 的集合,
{
"title" : "Post 1 Title",
"bodyText": "body text for blog post 1",
"dateCreated": new Date(),
"category": "movie"
}
在某些情况下,帖子可能属于 2 个类别
{
"title" : "Post 1 Title",
"bodyText": "body text for blog post 1",
"dateCreated": new Date(),
"category": ["movie","drama"]
}
这仍然是一个不错的设计,并且可以很好地处理大量数据。由于所有相关数据都存储在一个位置,这是 NoSQL 的真正优势,操作性能也将得到改善。
关于mongodb - 环回 : Saving one-to-many relations in MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29758144/
在railstutorial中,作者为什么选择使用这个(代码list10.25):http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-usersnamespace:dbdodesc"Filldatabasewithsampledata"task:populate=>:environmentdoRake::Task['db:reset'].invokeUser.create!(:name=>"ExampleUser",:email=>"example@railstutorial.org",:passwo
从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak
我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article
我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
我需要一个表,其中行实际上是2行表,一个嵌套表是..我怎样才能在Prawn中做到这一点?也许我需要延期..但哪一个? 最佳答案 现在支持子表:Prawn::Document.generate("subtable.pdf")do|pdf|subtable=pdf.make_table([["sub"],["table"]])pdf.table([[subtable,"original"]])end 关于ruby-on-rails-PrawnPDF:Ineedtogeneratenested
我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use
给定以下方法:defsome_method:valueend以下语句按我的预期工作:some_method||:other#=>:valuex=some_method||:other#=>:value但是下面语句的行为让我感到困惑:some_method=some_method||:other#=>:other它按预期创建了一个名为some_method的局部变量,随后对some_method的调用返回该局部变量的值。但为什么它分配:other而不是:value呢?我知道这可能不是一件明智的事情,并且可以看出它可能有多么模棱两可,但我认为应该在考虑作业之前评估作业的右侧...我已经在R