@@ -113,15 +113,16 @@ class TopicService extends Service {
113113 * @param {String } replyId 回复ID
114114 * @param {Function } callback 回调函数
115115 */
116- async updateLastReply ( topicId , replyId ) {
117- const topic = await this . ctx . model . Topic . findOne ( { _id : topicId } ) . exec ( ) ;
118- if ( ! topic ) {
119- return ;
120- }
121- topic . last_reply = replyId ;
122- topic . last_reply_at = new Date ( ) ;
123- topic . reply_count += 1 ;
124- return topic . save ( ) ;
116+ updateLastReply ( topicId , replyId ) {
117+ const update = {
118+ last_reply : replyId ,
119+ last_reply_at : new Date ( ) ,
120+ $inc : {
121+ reply_count : 1 ,
122+ } ,
123+ } ;
124+ const opts = { new : true } ;
125+ return this . ctx . model . Topic . findByIdAndUpdate ( topicId , update , opts ) . exec ( ) ;
125126 }
126127
127128 /*
@@ -138,20 +139,33 @@ class TopicService extends Service {
138139 * @param {String } id 主题ID
139140 */
140141 async reduceCount ( id ) {
141- const topic = await this . ctx . model . Topic . findOne ( { _id : id } ) . exec ( ) ;
142+ const update = { $inc : { reply_count : - 1 } } ;
143+ const reply = await this . service . reply . getLastReplyByTopId ( id ) ;
144+ if ( reply ) {
145+ update . last_reply = reply . _id ;
146+ } else {
147+ update . last_reply = null ;
148+ }
149+ const opts = { new : true } ;
150+
151+ const topic = await this . ctx . model . Topic . findByIdAndUpdate ( id , update , opts ) . exec ( ) ;
142152 if ( ! topic ) {
143153 throw new Error ( '该主题不存在' ) ;
144154 }
145155
146- topic . reply_count -= 1 ;
147- const reply = await this . service . reply . getLastReplyByTopId ( id ) ;
148- if ( reply . length !== 0 ) {
149- topic . last_reply = reply [ 0 ] . _id ;
150- } else {
151- topic . last_reply = null ;
152- }
156+ return topic ;
157+ }
153158
154- return topic . save ( ) ;
159+ incrementVisitCount ( id ) {
160+ const query = { _id : id } ;
161+ const update = { $inc : { visit_count : 1 } } ;
162+ return this . ctx . model . Topic . findByIdAndUpdate ( query , update ) . exec ( ) ;
163+ }
164+
165+ incrementCollectCount ( id ) {
166+ const query = { _id : id } ;
167+ const update = { $inc : { collect_count : 1 } } ;
168+ return this . ctx . model . Topic . findByIdAndUpdate ( query , update ) . exec ( ) ;
155169 }
156170
157171 newAndSave ( title , content , tab , authorId ) {
0 commit comments