
文章目录
mongodb不是传统的关系型数据库,我们可以使用monogoose方便的将多个表关联起来,实现一对多、多对多的数据表存储和查询功能。
本文已最常见的一对多关系模型,介绍简单的数据模型定义、存储、查询。
我们创建一个Person模型和一个Story模型,其中一个Person对应多个Story,也就是典型的一对多关系。
创建PersonSchema时,不需要为其指定_id属性,因为数据库会自动为其添加主键属性。
由于一个Person对象可以拥有多个Story对象,所以需要添加一个stories数组属性,存储与其关联的Story。
具体代码如下:
const PersonSchema = new Schema({
// _id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
})
问题解答
其中的Schema.Types.ObjectId是一种内置的特殊类型,专门用来表示对象的ID
官方解读:An ObjectId is a special type typically used for unique identifiers.
每个Story都有一个唯一的author,也就是一个Person对象。和普通的属性不同的是,我们需要指定引用属性的类型和引用的模型名称。同样的,每个Story对象还可以拥有多个fans,同样是Person对象。这里实际上有一个循环的引用。
如果学习过关系型数据库的同学,可能对这里非常容易了解。
const StorySchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
})
创建模型需要使用mongoose.model方法,该方法可以接收三个参数,其中:
StorySchema和PersonSchema创建了一个Story模型和一个Person模型const Story = mongoose.model('Story', StorySchema, 'tb_story')
const Person = mongoose.model('Person', PersonSchema, 'tb_person')
使用mongoose可以非常简单的使用面向对象的方式完成数据的存取。
创建一个名为xiaoming的Person对象,然后再创建一个Story,并使其引用Person._id属性。
let p1 = new Person({
name: 'xiaoming',
age: 12
})
let s1 = new Story({
title: 'The life of snow white and the dwarfs',
author: p1._id
})
s1.fans.push(p1.id)
问题解读
这里有一个不符合常理的地方,就是我在这里把故事的作者设为了故事的粉丝~~
使用模型的.save()方法存储对象的数据到数据库中。
p1.save().then(person => {
console.log('Pserson save success.\n', person)
s1.save().then(story => {
console.log('Story save success.\n', story)
})
})
代码指向结果如下:
Pserson save success.
{
name: 'xiaoming',
age: 12,
stories: [],
_id: new ObjectId("62ef6fb11c8795f4e1327adb"), //注意,这里对应了下面的Story.author
__v: 0
}
Story save success.
{
author: new ObjectId("62ef6fb11c8795f4e1327adb"), //注意,这里对应了上面的Person._id
title: 'The life of snow white and the dwarfs',
fans: [ new ObjectId("62ef6fb11c8795f4e1327adb") ],
_id: new ObjectId("62ef6fb11c8795f4e1327adc"),
__v: 0
}
这样数据存储工作就完成了。
Story.findOne({ title: 'The life of snow white and the dwarfs' })
.populate('author').then(story => {
console.log(story.author.name)
})
执行结果会输出:xiaoming
2. 使用故事标题,查询粉丝信息
Story.findOne({ title: 'The life of snow white and the dwarfs' })
.populate('fans').then(story => {
console.log(story.fans)
})
代码执行结果:
[
{
name: 'xiaoming',
age: 12,
stories: [],
_id: new ObjectId("62ef781a8123a8ec47f40736"),
__v: 0
}
]
const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect('mongodb://ahohAdmin:123456@localhost:27017/db_ahoh')
.then('database connected')
.catch(err => console.log(err))
const PersonSchema = new Schema({
// _id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
})
const StorySchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
})
const Story = mongoose.model('Story', StorySchema, 'tb_story')
const Person = mongoose.model('Person', PersonSchema, 'tb_person')
let p1 = new Person({
name: 'xiaoming',
age: 12
})
let s1 = new Story({
title: 'The life of snow white and the dwarfs',
author: p1._id
})
s1.fans.push(p1.id)
p1.save().then(person => {
console.log('Pserson save success.\n', person)
s1.save().then(story => {
console.log('Story save success.\n', story)
})
})
Story.findOne({ title: 'The life of snow white and the dwarfs' })
.populate('author').then(story => {
console.log(story.author.name)
})
Story.findOne({ title: 'The life of snow white and the dwarfs' }).populate('fans').then(story => {
console.log(story.fans)
})
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h