DoraCMS留言模块的重构
折腾了几天在重构message的代码,一直想要优化这一块,message对象之前是这个样子的
折腾了几天在重构message的代码,一直想要优化这一块,message对象之前是这个样子的:
var mongoose = require('mongoose'); var shortid = require('shortid'); var Schema = mongoose.Schema; var message = new Schema({ _id: { type: String, unique: true, 'default': shortid.generate }, contentId : String, //留言对应的内容ID contentTitle : String, // 留言对应的内容标题 uName : String, // 评论者用户名 uid : String, // 评论者ID uEmail : String, // 评论者邮箱 ulogo : String, // 评论者头像 relationUid : String, // 关联用户ID relationEmail : String, // 关联用户邮箱(被评论者) date: { type: Date, default: Date.now }, // 留言时间 praiseNum : {type : Number , default : 0}, // 被赞次数 hasPraise : {type : Boolean , default : false}, // 当前是否已被点赞 praiseMembers : String, // 点赞用户id集合 content: { type : String , default : "输入评论内容..."}// 留言内容 }); var Message = mongoose.model("Message",message); module.exports = Message;
问题在哪呢?重复的属性太多,不灵活。记录了留言者和关联对象的属性,如果遇到后面的拓展,例如需要留言者的更多信息怎么办呢?或者关联者的信息发生变化呢,保存的都是静态信息,这条message也就没有存在的意义了。最近也在看mongoose的相关文档,提到了DBref,也就是关联对象,当属性和相关对象关联后,通过mongoose的populate查询方式就可以查出相关联对象的详细信息,这样,我就不需要再记录多余的属性了。修改后的代码是这样的:
var mongoose = require('mongoose'); var shortid = require('shortid'); var Schema = mongoose.Schema; var AdminUser = require('./AdminUser'); var User = require('./User'); var MessageSchema = new Schema({ _id: { type: String, unique: true, 'default': shortid.generate }, contentId : String, // 留言对应的内容ID contentTitle : String, // 留言对应的内容标题 author : { type : String, ref : 'User' }, // 留言者ID replyAuthor : { type : String, ref : 'User' }, // 被回复者ID adminAuthor : { type : String, ref : 'AdminUser' },// 管理员ID utype : {type : String ,default : '0'}, // 评论者类型 0,普通用户,1,管理员 relationMsgId : String, // 关联的留言Id date: { type: Date, default: Date.now }, // 留言时间 praiseNum : {type : Number , default : 0}, // 被赞次数 hasPraise : {type : Boolean , default : false}, // 当前是否已被点赞 praiseMembers : String, // 点赞用户id集合 content: { type : String , default : "输入评论内容..."}// 留言内容 }); MessageSchema.post('save',function(doc){ console.log('new message has been add success'); }); var Message = mongoose.model("Message",MessageSchema); module.exports = Message;
如何查询呢?
Message.find({'contentId' : contentId}).populate('author').exec(function(err,callBack));
非常简单。
由于改动比较大,不得已把大家的留言全部清空了,在这里说声抱歉了。只为系统更加完善和稳定,除message模块外,其它地方也有比较大的改动和优化,上线几天测一下,没大问题再commit到代码库中。
很赞哦! ( 0
)
相关文章
- Node.js 入门
- nodeJs基础教程系列(3)——建立githubs项目
- nodeJs基础教程系列(1)——安装Node.js
- nodeJs基础教程系列(6)——Promise 模式的Q库
- Atom 更为先进的文本代码编辑器 - 由 Github 打造的下一代编程开发利器
- bootstrap 3.3 模态框垂直居中问题
- js字符串操作
- js鼠标滑轮滚动事件绑定(兼容主流浏览器)
- 视频:Windows 安装FTP服务 (基于Windows2008 IIS配置FTP站点 )
- 屌丝为什么找不到女朋友
- nodejs 利用GraphicsMagick和gm组件创建图片缩略图
- 马云终于离职了,最后他说了什么?