自动推送新聊天信息并更新Firebase实时数据库上的lastMessage值

自动推送新聊天信息并更新Firebase实时数据库上的lastMessage值,firebase,firebase-realtime-database,transactions,atomic,Firebase,Firebase Realtime Database,Transactions,Atomic,我将聊天信息和聊天元数据存储在此结构中: project | -- chats | -- 1 | -- -MFBvnTIQgVKdyFzDMpy | -- message: "hello" | -- -MEZutiaxOthE-7nDOkA | -- message: "how are you?" | -- 2

我将聊天信息和聊天元数据存储在此结构中:

project
|
-- chats
   |
   -- 1
      |
      -- -MFBvnTIQgVKdyFzDMpy
         |
         -- message: "hello"
      |
      -- -MEZutiaxOthE-7nDOkA
         |
         -- message: "how are you?"
   |
   -- 2
      |
      -- -MENuu8TjwWrBTkIzue_
         |
         -- message: "hi"
      |
      -- -MFBTqEqhR9Dtv3MlMd6
         |
         -- message: "you good?"
|
-- chatMetadata
   |
   -- 1
      |
      -- lastMessage: "how are you?"
   |
   -- 2
      |
      -- lastMessage: "you good?"

每当用户向特定聊天室提交新的聊天信息时,该聊天室的lastMessage属性应在chatMetadata中更新。该过程包含两个单独的操作:
.push()
用于推送新的聊天信息,以及
.update()
用于更新lastMessage属性。如果多个用户可以同时向特定聊天室提交消息,我如何保证lastMessage始终等于last pushed chat message?

云功能必须使用实时数据库触发器才能做到这一点

// Listens for new messages added to /chats/:chatId/ and creates an
// uppercase version of the message to /chatMetadata/:chatId/

exports.updateLastMessage = functions.database.ref('/chats/{chatId}/')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      
      // You must return a Promise when performing asynchronous tasks inside a Functions 
      // Writing the lastMessage node 
      return snapshot.ref.parent.parent.child('chatMetadata').child(context.params.chatId).set({lastMessage: original.message});
});