node.js - 如何使用 Mongoose 将新对象添加到 MongoDB 中特定对象的数组中?
问题描述
这是我的模型,并且已经在数据库中有一些文档。
我想将一个新对象推送到like_count
现有帖子文档的数组中,其中postId
将与给定值匹配。
我第一次使用猫鼬。我已经搜索过,但没有找到像这样的用例。无法理解如何编写逻辑。需要帮忙。
另外,告诉我我是如何定义Users
模型的,还是应该为那些数组对象使用子文档?
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
andarrayFilters
运算符来实现这一点:
await User.updateOne({
'recent_posts.postId': postId
}, {
$push: {
'recent_posts.$[elem].like_count': newLikeCountObject
}
}, {
arrayFilters: [{'elem.postId': postId}]
})
推荐阅读
- java - 搜索标题包含关键字的书籍并按标题排序(按字母顺序)返回
- reactjs - RN - 如何从 Slider 获取标签?
- opengl - 像素完美:选择正确的校正(OpenGL)
- mysql - 数组中的 Codeigniter MySQL 数据
- reactjs - 如何将值传递给我通过 onClick 事件从另一个组件获取的组件
- python - 尝试按类抓取 HTML 跨度值,但返回错误
- php - 如何使用 JQUERY 将 PHP 变量传递给 .JS 文件?
- ruby-on-rails - 防止在祖先链中查找方法(method_missing)
- java - 如何在 Java 字符串中使用波浪号 ~
- python - 使用 Python 和 BeautifulSoup 为 Yahoo 新闻和 Bing 新闻生成 URL