mongodb - 带有 $in 和 arrayFilters 的 mongodb updateMany
问题描述
我有以下集合结构:
{
_id: userId,
posts: [{ _id: postId, views: 0 }]
}
我的输入如下:
- 带有用户 ID 的数组
- 带有帖子 ID 的数组
有了这些信息,我想views
为每个匹配的用户/帖子增加,我试过这样:
await Post.updateMany(
{
_id: {
$in: userIds
}
},
{
$inc: {
"posts.$[elem].views": 1
}
},
{
arrayFilters: [
{
"elem._id": {
$in: postIds
}
}
],
upsert: true
}
);
但我得到了错误:
更新中未使用标识符“elem”的数组过滤器 { $setOnInsert: { __v: 0 } }
我还确保 ID 是 ObjectId 而不是字符串。
那么我在这里做错了什么?
解决方案
那么该查询工作正常,我只是忘了将属性添加views
到我的猫鼬模型中
添加views
到我的模型后,它起作用了
const postSchema = new mongoose.Schema({
_id: {
type: mongoose.Types.ObjectId
},
posts: [
{
_id: {
type: mongoose.Types.ObjectId
},
userid: {
type: mongoose.Types.ObjectId
},
images: {
type: Object
},
category: {
type: String
},
description: {
type: String
},
hashtags: {
type: Array
},
comments: {
type: Array
},
likesUser: {
type: Array
},
time: {
type: Number
},
loading: {
type: Boolean,
default: true
},
views: {
type: Number
}
}
]
});
推荐阅读
- java - JSoup - 选择不在链接内的图像
- php - 在mysql查询中获取下一行
- javascript - 如何使用 Angular 7 在 formControl 中设置文件?
- reactjs - 如何在其中获取 API 提供的记录值
? - android - 尝试将 downloadUri 添加到 Firestore 文档时出错。“无法序列化对象。超过最大深度 500”
- python - 如何解决导入 tkinter 模块的问题
- excel - Excel VBA - 从多个文本文件中提取包含特定名称的行
- web-scraping - 用户警告:未安装soupsieve 软件包。不能使用 CSS 选择器
- ecmascript-6 - 为什么 var 和 let 都抛出重新声明错误?
- javascript - 无法在动态创建的输入 ID 上 getDocumentById