0

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.

C.O.D.E
  • 885
  • 8
  • 19
  • You could use a _list function to filter before sending to the client, though you still have to loop every single chat from all users to do so. You could output your view per-user, and collate them yourself on the client-side. – Dominic Barnes Dec 10 '12 at 18:25

1 Answers1

0

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.

Dmitrii Sorin
  • 3,855
  • 4
  • 31
  • 40
  • Celebrated too soon! it didn't work actually :(!! Maybe it's the way i'm putting startkey and endkey on the view. How do I pass them using cradle? I'm doing it this way: couchdb.view('chat/history', filterRange, function (err, results) { results.forEach(function (row) { console.log(row.message + '\n'); }); }); it's giving me "Cannot call method 'forEach' of undefined. – C.O.D.E Dec 15 '12 at 22:08
  • I finally was able to solve the problem through some heavy searching and by using your reply. Thanks :)!! – C.O.D.E Dec 16 '12 at 20:43