简体   繁体   中英

Update array of objects in RethinkDB

I have the following document representing a chat room, where the timestamp in the member objects represents that particular user's last activity in the room.

{
  "id":  "4ff130cc-3201-4a30-8a4c-5ce4303d28d0",
  "name": "General chat",
  "members": [
     {
       "timestamp": 1437074682224 ,
       "user_id": "bdb4c00c-0ce8-4e22-9331-38b5c4b083e4"
     },
     {
       "timestamp": 1437074693805 ,
       "user_id": "7708ebc6-915b-4bfd-b63e-849bacefa201"
     }
  ]
}

When the user eg joins the room, I would like to update the timestamp. It seems like a trivial operation, but I cannot get it to work.

I am using the official JavaScript driver. How do I update the timestamp with a given user_id?

I ended up filtering out every member except the one I'm interested in, and appending a new object to it.

r.db("chat").table("rooms").get("room_id").update(function(room) {
  return {
    members: room("members").filter(function (member) {
      return member("user_id").ne("relevant_user_id");
    }).append({ user_id: "relevant_user_id", timestamp: 1337 })
  };
});

Not sure this is the "right way" to do it.

I may have misunderstood your question but try this

function updateTime(user_id) {
  for (var i = 0; i < members.length; i++) {
    if (members[i].user_id == user_id) {
      members[i].timestamp = /*current time*/
      break;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM