I have a user schema like that:

name: String,
nick: String,
email: String,
password: String,

bio: String,
color: String,
followers: [String],
followings: [String],

posts: [{
    author: {
        name: String,
        nick: String
    content: String,
    date: Date,
    simpleDate: String,
    color: String,
    likes: [String]

I want to when user push the like button my backend take the id of post and add user's nick to array that named "likes". So I want to find the object that has post that has this id and add a new string to likes array of it.

User.findOneAndUpdate({'posts._id': req.params.postId},{$push:{posts:{likes:{likes:req.header.authenticatedUser.nick}}}},
    (err,result) => {...});

I tried something like that but it's not working and looks like very wrong.

How can I find and push to nested object like that?


When I use the code below

User.findOneAndUpdate({'posts._id': req.params.postId},{"$push":{"posts":{"likes":req.header.authenticatedUser.nick}}},(err,results)=>{

it adds a likes array to posts. But I want add my usurname to likes array of post that has index 2 enter image description here

  • Can you add the error which you got? – Yunus UYANIK Oct 31 '20 at 8:46
  • CastError: Cast to embedded failed for value "{ likes: { likes: 'zuck' } }" at path "posts" My way is totally wrong. I can't find the even correct post. – zer0 Oct 31 '20 at 9:10

Before the change your application code, you should try to mongo shell this command on your test environment.


enter image description here

  • I add a photo to my question, can you look at that? – zer0 Oct 31 '20 at 9:47
  • Yes, I changed my answer. Hope I understood your question. – Yunus UYANIK Oct 31 '20 at 10:51
  • There is one more thing: The program must determine the index of the post that has req.params.postId. – zer0 Oct 31 '20 at 11:08
  • Oh, I see. First of all, you have to get an index number and set it to a variable. After that, you can use this like the above. – Yunus UYANIK Oct 31 '20 at 11:12
  • Is there any way to get both them via one query? Or how I can use that variable in the that string "post.2.likes" ? The first idea is var q = "post."+indexNumber+".likes" but it's ugly. – zer0 Oct 31 '20 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.