DoraCMS

您现在的位置是:首页>文档内容页

文档详情

DoraCMS留言模块的重构

doramart 2015-11-11 20:41:48 原创教程225291
折腾了几天在重构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到代码库中。

文章评论

取消回复
登录 参与评论

评论列表(