要回覆使用者讯息的话,我们必须要从资料库内找出使用者发过来的讯息,取得reply Token后再回覆给使用者.
MongoDB的Query查询方式跟关连式资料库相比是不同的,以下我们会透过实作查询接口来带大家完成.
资料结构长相
{ _id: ObjectId("642910bf2e7be725ecce6b3b"), destination: <channel destination>, events: [ { type: 'message', message: { _id: <message _id>, type: 'text', text: <user message> }, webhookEventId: <webhookEventId>, deliveryContext: { isRedelivery: false }, timestamp: '1680412863529', source: { type: 'user', userId: <userId> }, replyToken: <your replyToken>, mode: 'active' } ], _class: 'com.example.lineMsgDemo.model.LineMsgBack' }
查询repository
public interface LineMessageRepository extends MongoRepository<LineMsgBack, String>{@Query("{'events.source.userId' : ?0 } ")public List<LineMsgBack> findByUserId(String userId);}
可以发现它是用类似python的语法去映照查询字串的
Controller
//根据使用者ID查询@GetMapping("/search/user/{userId}")public List<LineMsgBack> searchByUserId(@PathVariable String userId) {List<LineMsgBack> result = lineMessageRepository.findByUserId(userId);return result;}
这样就完成使用者资料查询接口了喔,很简单吧
最后一篇我们会讲要如何利用replyToken回覆使用者资讯
Line Message API + MongoDB 串接实作(四)发送讯息