Stuart Fong
Stuart Fong

Reputation: 633

Mongoose: change specific element in array that matches query

Schema:

var User = new Schema({
      userId: String,
      name: String,
      lastLogin: Date,
      lastPost: Date,
      followers: [String],
      following: [String],
      posts: [{
          date: Date,
          title: String,
          likes: Number,
          public: Boolean,
          comments: [{
              date: Date,
              comment: String,
              postedBy: String
          }],
          modules:[{
              moduleType: String,
              entries: [{
                  file: String,
                  date: Date
              }]
          }]
      }]
    
    });

Query:

await User.updateOne({
    $and:[
        { userId: id },
        { posts: { $elemMatch: { title: activityTitle }}}
    ]}, 
    { $inc: { "posts.0.likes": 1 }}
)
.exec()
.then(() => {
    console.log(`Liked activity '${activityTitle}'`)
})

This query obviously only increases the likes for the first element in posts. But what I am trying to do is increase the likes for the post that contains the title: activityTitle.

For example a user, User1, can have 3 posts with titles, post1, post2, post3. But I want to increase the likes on post3. I have no way of knowing which post to like since when I query, it returns the whole array and not just the element with the same title.

Upvotes: 0

Views: 33

Answers (1)

HellCatVN
HellCatVN

Reputation: 876

You're close to result. You should use dot notation in your use of the $ update operator to do that:

User.updateOne({
    $and:[
        { userId: id },
        { posts: { $elemMatch: { title: activityTitle }}}
    ]}, 
    { $inc: { "posts.$.likes": 1 }}
)
.exec()
.then(() => {
    console.log(`Liked activity '${activityTitle}'`)
})

Upvotes: 1

Related Questions