$ PullAll跨文档-猫鼬

时间:2020-04-28 15:17:42

标签: node.js mongodb mongoose mongodb-query

在我的示例中,我试图找到一种从用户的监视列表中删除listingId条目的有效方法。每个用户集合都有一个监视列表字符串数组,用户可以在其中存储他们正在监视的项目。

示例文档:

 "watchlist": [
    "5ea8449842025217ccff6aec",
    "5ea844eb42025217ccff6aee",
    "5ea8452b42025217ccff6af1"
  ],

为了维护一个干净的数据库,我正在创建一个azure计时器函数来经常部署,以查找和删除不再存在的列表的监视列表项。可能有许多用户在其监视列表中具有相同的列表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 }

1 个答案:

答案 0 :(得分:1)

根据您当前的代码:

 User.deleteMany()
 /** Will actually delete docs from users collection, you need to use .update() or .findAndUpdate() to alter fields inside docs */

如果res是列表ID的数组,则可以这样做:

Post.distinct("_id", { watchlistCleaned: false, auctionEndDateTime: { $lte: Date.now() } }).then((res) => {
  /** So `res` will be an array of unique `_id`'s of Post collection which matches given conditions */
  User.updateMany(
    { watchlist: { $in: res } }, /** get users who have listings ids  */
    {$pullAll : { watchlist : res } } /** pull all listing ids */
  );
});