Question

I'm currently using Couchdb to save chat history between two users. My db contains every inserted messages entered by every user. They are entered like this:

{
  _id: (timestamp),
  from: sender,
  to: receiver,
  message: msg
}

I have a view coded like this:

   function(doc) {
     if (doc.from && doc.to){
         (doc._id, doc);
     }
   }

I'm having a hard time thinking of an idea to retrieve a chat conversion between two users based on my current setup.

I did it the following way inside the view function:

res.forEach(function (row) {
    if(row.from != null || row.to != null){
          if((row.from == socket.username && row.to == receiver) || (row.from == receiver && row.to == socket.username)){
             MsgHistoryContent += row.message + '\n';
          }
    }
});

yet that didn't retrieved all conversation between just two users as it retrieves all the messages from every user.

Anybody can give me a lead? Any help would be appreciated.

P.S: i'm using node.js and cradle.

Was it helpful?

Solution

You can create a map function like this:

function(doc) {
    var key = [doc.from, doc.to].sort(function (a, b) {
        return a.localeCompare(b);
    });

    emit(key.concat(doc._id), doc);
}

Then you will be able to get the conversation between users by querying '?startkey=["user1", "user2"]&endkey=["user1", "user2", {}]'. Of course both start- and endkeys 0 and 1 indexes should be alphabet-sorted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top