node.js开发之多人博客
网站搭建:Express4.13.1+mongoDB 模板引擎采用jade
网站功能不断完善中
项目主要结构
:入口文件
—:路由
:数据库的“表”,monogDB里的模式 :将模式具象成可操作的模型 :处理路由里的函数,渲染页面,处理页面逻辑,操作数据库。
:页面 :静态资源(css/js/image)
关于.populate()
因为MongoDB是文档型数据库,所以它没有关系型数据库[joins],为了解决这个问题,Mongoose封装了一个Population功能。使用Population可以实现在一个 document 中填充其他 collection(s) 的 document(s)。
————以下的为例:
var ObjectId = Schema.Types.ObjectId
user:{
type: ObjectId,
ref: user
},
在定义Schema的时候,如果设置某个 field 关联另一个Schema,那么在获取 document 的时候就可以使用 Population 功能通过关联Schema的 field 找到关联的另一个 document,并且用被关联 document 的内容替换掉原来关联字段(field)的内容。 下的 index.js
postModel
.find()
.populate(user) //关联字段
.sort({
"meta.updateAt":-1})
.exec(function(err,post){
userModel.find(function(err,user) {
if (err) {
console.log(err)
}
res.render(index, {
title: 首页,
post: post,
head: user
})
})
})
查看数据库:
关于.populate()我遇到的问题
也是因为MongoDB是非关系型数据库的原因,“字段”可随意添加修改,在开发初期,为了测试数据库的运作,我会不时向schema中添加新的字段,所以当在回到测试多表连接查询的页面时,提示错误信息*the property of xxx is underfined* 解决:清空数据库,统一字段。(虽然是很简单的错误,但是在开发过程中错误发现时我却没有意识到这一点,因此走了一些弯路)
