mongoose 合并没有重复项的数组|节点|蒙戈数据库

0dxa2lsx  于 2023-02-23  发布在  Go
关注(0)|答案(3)|浏览(131)

我有两个不同的模型,UsersTeams,其中Teams引用了Users。我试图获取用户所属的所有团队,然后获取这些团队中的所有成员用户,并将它们合并到一个数组中,不重复。我只设法获取了用户所属的团队。有什么想法吗?(我是新手)
我的代码:

router.get('/mention', verifyToken, async (req: any, res: any) => {

   const user = req.user as IUser;

   let allTeamsofOneUser = await Teams.find({
      user: user._id
   });
   res.send(allTeamsofOneUser);

})

export default router;

我的代码结果:

[
    {
        "user": [
            "5f9e9ec9974ce02dc8f606e1",
            "5fa42303e2c49841b849fd21",
            "5fa2c3a50c061b558058f60f"
        ],
        "_id": "5fa533513836f503d826e6f2",
        "name": "Myteam",
        "createdAt": "2020-11-06T11:28:17.047Z",
        "updatedAt": "2020-11-06T11:28:17.047Z",
        "__v": 0
    },
    {
        "user": [
            "5f9e9ec9974ce02dc8f606e1",
            "5fa42303e2c49841b849fd21"
        ],
        "_id": "5faa73e583b15448d4ad93c7",
        "name": "teamteam",
        "createdAt": "2020-11-10T11:05:09.832Z",
        "updatedAt": "2020-11-10T11:05:09.832Z",
        "__v": 0
    }
]
r3i60tvu

r3i60tvu1#

迭代团队,获取所有用户并将其放入一个数组中,然后从数组中筛选唯一用户。

let uniqueUsers = allTeamsofOneUser.reduce((acc, team) => {
    acc.push(...team["user"]);
    return acc;
}, []).filter((value, index, self) => self.indexOf(value) === index);
gkl3eglg

gkl3eglg2#

我认为你应该扫描每个团队,然后扫描每个团队中的每个用户,最后检查一下你以前不知道他/她。

let uniqueUsers = [];
allTeamsofOneUser.forEach( team => {
  team.user.forEach( user => {
    if(!uniqueUsers.some( userCandidate => user._id === userCandidate._id)) {
      uniqueUsers.push(userCandidate);
    }
  });    
});
wrrgggsh

wrrgggsh3#

我在 Mongoose 文档上找到了解决方案,

User.findOneAndUpdate(
            { _id },
            { $addToSet: { trackedGeckoCoins: { $each: geckoCoinIds } } },
            { new: true, projection: 'trackedGeckoCoins' }
          )
            .then((doc) => res.status(200).json(doc))
            .catch(sendStatus500)

来源:https://www.mongodb.com/docs/manual/reference/operator/update/each/

相关问题