Mongoose:更改数组中匹配查询的特定元素

模式:

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
              }]
          }]
      }]
    
    });

查询:

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

这个查询显然只增加了post中第一个元素的点赞数。但我正在尝试做的是增加包含title: activityTitle的帖子的点赞。

例如,用户User1可以有3个标题为post1, post2, post3的帖子。但我想增加post3上的点赞数。我没有办法知道我喜欢哪个帖子,因为当我查询时,它返回整个数组,而不仅仅是具有相同标题的元素。

转载请注明出处:http://www.wje4.com/article/20230526/2402693.html