模式:
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上的点赞数。我没有办法知道我喜欢哪个帖子,因为当我查询时,它返回整个数组,而不仅仅是具有相同标题的元素。
发布于 2021-05-20 14:31:21
你离结果很近了。您应该在使用$ update operator时使用点符号来做到这一点:
User.updateOne({
$and:[
{ userId: id },
{ posts: { $elemMatch: { title: activityTitle }}}
]},
{ $inc: { "posts.$.likes": 1 }}
)
.exec()
.then(() => {
console.log(`Liked activity '${activityTitle}'`)
})https://stackoverflow.com/questions/67611392
复制相似问题