Home > Software engineering >  findOneAndUpdate. Select array of messages, select message object and update likes array inside it
findOneAndUpdate. Select array of messages, select message object and update likes array inside it

Time:05-16

I use mongoose findOneAndUpdate method, but could't achieve the result. I always get the same object back. No errors. Here's my code. User object:

{
    "_id" : ObjectId("6273b64b607b1d228795f067"),
    "username" : "User1",
    "mail" : "[email protected]",
    "password" : "$2b$12$NrJ9E8xSz1iCfmIPY0snC.e6x4B/ymqtH.at9uUWaCXTQUwJi1eem",
    "messages" : [ 
        {
            "message" : "Brand new message",
            "date" : 1652508162106.0,
            "author" : "User1",
            "likes" : []
        }
    ],
    "__v" : 16
}

Here's my backend code:

const {author} = req.params;
const {mssg, whoLiked} = req.body;

   User.findOneAndUpdate({username: author, messages: mssg}, {$push: {likes: whoLiked}}, {new: true}, (err, user)=>{
     err && console.log(err);
     res.send(user)
   })
 })

Nothing udpates. Maybe I try to pick the message the wrong way... I know, it's possible to do this in one action. But I can't figure it out. What'd you say guys?

CodePudding user response:

Ok, I finaly figured it out. Here's the code to push new person whoLiked into the likes array.

 router.post("/:author/likeThePost", (req,res)=>{
const {author} = req.params;
const {mssg, whoLiked} = req.body;
console.log(mssg, whoLiked);
   User.findOneAndUpdate({username: author, "messages.date": mssg.date}, {$push: {"messages.$.likes": whoLiked}}, {new: true}, (err, user)=>{
     err && console.log(err);
     res.send(user.messages)
   })
 })

Some comments:

  1. I use mongoose findOneAndUpdate method. As far as I know there's the same node.js method, but the code might be different.
  2. Let's break down the code a bit:
  • first you find the user who wrote the original message by username: "Some user name"
  • then you pick the message you need by some unique value. In my case this is just the timestamp: "messages.date": mssg.date . Same user just can't post two messages with the same Date.now() timestamp.
  • then you do what you need with the message've been picked:{$push: {"messages.$.likes": whoLiked}} Second dollar sign stands for picking right message. Looks like it's the index of it.
  • Related