$PullAll 跨文档 - 猫鼬 [英] $PullAll across documents - mongoose

查看:48
本文介绍了$PullAll 跨文档 - 猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to figure out an efficient way to remove entries of a listingId from a user's watchlist in my example. Each user collection has a watchlist string array where users can store the items they are watching.

示例文档:

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

为了维护一个干净的数据库,我正在创建一个 azure 计时器函数来经常部署以查找和删除不再存在的列表项的监视列表项.可能有许多用户在他们的监视列表中具有相同的列表 ID 条目.所以我需要定期检查清理它们.

In order to maintain a clean database I'm creating an azure timer function to deploy every so often to find and remove watchlist items of listings that no longer exist anymore. There could be many users that have the same listing id entry in their watchlist. So I need to clean those up with regular checks.

查询:

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 }

推荐答案

来自您当前的代码:

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

如果 res 是一个列表 id 数组,那么你可以这样做:

If res is an array of listings id's then you can do this :

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 */
  );
});

这篇关于$PullAll 跨文档 - 猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆