【发布时间】:2020-08-12 11:27:00
【问题描述】:
在我的示例中,我试图找出一种有效的方法来从用户的关注列表中删除 listId 的条目。每个用户集合都有一个监视列表字符串数组,用户可以在其中存储他们正在观看的项目。
示例文档:
"watchlist": [
"5ea8449842025217ccff6aec",
"5ea844eb42025217ccff6aee",
"5ea8452b42025217ccff6af1"
],
为了维护一个干净的数据库,我正在创建一个 azure timer 函数来经常部署以查找和删除不再存在的列表项的监视列表项。可能有许多用户在其监视列表中具有相同的列表 ID 条目。所以我需要定期检查清理它们。
查询:
Post.find({
$and: [
{ watchlistCleaned: false },
{ auctionEndDateTime: { $lte: Date.now() } }
]
}).select("_id").then((res) => {
for (let i = 0; i < res.length; i++) {
console.log("res[i]")
console.log(res[i]._id)
//pretty sure this would remove the whole watchlist instead of one item so this wouldn't be ideal.
//It's needs to pull the items out on a multiple document scale
// User.deleteMany({ _id: res[i]._id },{watchlist: {$in: res[i]}})
}
})
期望的输出:
{ _id: 5ea84412048bf54164fe9983 }
res[i]
{ _id: 5ea8449842025217ccff6aec }
res[i]
{ _id: 5ea844c042025217ccff6aed }
res[i]
{ _id: 5ea844eb42025217ccff6aee }
res[i]
{ _id: 5ea844ed42025217ccff6aef }
res[i]
{ _id: 5ea844ee42025217ccff6af0 }
res[i]
{ _id: 5ea8452b42025217ccff6af1 }
res[i]
{ _id: 5ea85daac6e12a10b09a75a5 }
【问题讨论】:
-
res有什么作用?它是否有_id的关注列表项或_id的用户?还有这是什么watchlistGroup- 你的数组名称是watchlist还是watchlistGroup? -
我在上面添加了 res 输出。输出表示尚未为
watchlistCleaned或设置为 false 的列表,因此它不会两次清理相同的列表。监视列表组是一个错字。我刚才修好了。我在每个用户文档中的数组称为watchlist: [String] -
所以
res是需要从用户的watchlist数组中删除的字符串/ID 列表? -
正确。 res _ids 是一些用户文档中的列表 ID,因为他们将该列表添加到他们的监视列表中。这是为了清理旧列表的列表 ID
标签: node.js mongodb mongoose mongodb-query