【问题标题】:MongoDB monk collection name: UserX + UserYMongoDB和尚集合名称:UserX + UserY
【发布时间】:2020-10-19 20:25:13
【问题描述】:

使用前端 Vue.js,我们(用户)尝试加入私人聊天。 使用 MongoDB 将消息存储在集合“XY”中, 其中:

  • X - UserX._id (req.user._id)
  • Y - UserY._id(toUser._id - 从用户列表中选择的用户)

=> 集合名称“UserX+UserY”,类似于 5ef630dfbe431b28e0d97823 + 5ef4fa80c3a5071e2055b507 = 5ef630dfbe431b28e0d978235ef4fa80c3a5071e2055b507。

-在前端显示用户列表(通过从数据库中读取用户名帐户)

问题:

  1. UserX 通过选择(单击)一个 UserY 开始聊天 - 创建了 MongoDB 集合“UserX+UserY”

  2. UserY 点击 UserX - MongoDB 集合 "UserY+UserX"

当 UserY 尝试加入聊天时,我需要先获取已经存在的房间,让 UserY 加入,而不是创建另一个聊天。

从 roomName(collection) 中反转用户 ID 是问题所在。

我尝试通过按字典顺序比较集合名称中的子字符串来解决。 如果集合包含 BOTH 子字符串(用户 ID),我需要让用户加入该房间。子字符串的顺序并不重要。

  • 我将使用网络套接字让用户实时阅读消息。 Post 请求仅使用常规 HTTP 请求发出。

        if(toUserId !== myUserId) {
      // room id must have BOTH user 1 & user 2
      var rooms = db_room.find({ /* all */});
      var index = db_room.get({ $indexOfArray: [ myUserId + toUserId ] });
    
      var existingRoom1 = myUserId > toUserId // this lexicographically compares two strings
        ? myUserId + toUserId
        : toUserId + myUserId;
       var existingRoom2 = myUserId < toUserId
        ? myUserId + toUserId
        : toUserId + myUserId;
    
    // indexOf - search position by string === string
    // .includes - on letters, can be use x && y, substring of string => result boolean
    
     // if(rooms.includes(existingRoom1) + rooms.includes(existingRoom2))
     if(db_room.get( {$in: existingRoom1()} ) + db_room.get( {$in: existingRoom2} ))
        { // exists or not, true or false
    
          // find name of the room containing myUserId && toUserId
          // emit join in this.room (join with indexNr)
          if( index == -1 ) {
            index = rooms.indexOf(toUserId + myUserId);
          }// if not found
    
          console.log(`room ${room} exists: \n`);
          console.log(index);
    
          var roomXY = rooms[index];
          // true, emit Join event to clients.
          // MongoDB.getCollection(this.collection).insert({ UserX + UserY })
          //socket.join(roomXY, myUserId, toUserId);
          //var i = Object.keys(io.sockets.adapter.sids).indexOf(toUserId);
          console.log(`${toUserId} e nr ${i}`);
      } else {
       // create the room firsty, after join.
      }
    }
    

【问题讨论】:

    标签: node.js mongodb collections chat


    【解决方案1】:

    我建议简化您的房间命名代码。您可以让两个用户选择相同的房间名称而不检查数据库。因此,从顶部开始,您的代码可能是:

    if(toUserId !== myUserId) {
      let roomName = toUserID < myUserId ? toUserId+myUserId : myUserId+toUserId;
    

    现在,两个用户都可以检查数据库以查看该房间名称是否必须创建或已经存在,发出代码中引用的“加入”事件,然后发布消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-02
      • 2013-08-29
      • 2014-09-22
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      相关资源
      最近更新 更多