这是我的模型,并且数据库中已经有一些文档。
我想将新的 Object 推入现有帖子文档的like_count
数组中,其中postId
将与给定值匹配。
我第一次使用 猫鼬 。我已经搜索过但没有找到这样的用例。无法理解如何编写逻辑。需要帮助。
另外,请问我可以如何定义Users
模型,还是应该对那些数组对象使用 Sub-Document ?
const Users = new mongoose.Schema({
username: { type: String, unique: true },
recent_posts: [
{
postId: String,
posted_at_timestamp: Number,
like_count: [
{
count: Number,
created_at: { type: Date, default: Date.now }
}
],
comment_count: [
{
count: Number,
created_at: { type: Date, default: Date.now }
}
]
}
],
})
您可以使用$push
和arrayFilters
运算符来实现:
await User.updateOne({
'recent_posts.postId': postId
}, {
$push: {
'recent_posts.$[elem].like_count': newLikeCountObject
}
}, {
arrayFilters: [{'elem.postId': postId}]
})