javascript 从object express js mongodb数组内部的数组获取特定对象

amrnrhlw  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(121)

我在用户数组中有friends数组,我需要通过电子邮件获取特定用户的所有friendsapproved字段为true
在nodejs中,我有用户mongo模式

const UserSchema = mongoose.Schema({
     username : {type: String , required :true},
     email : {type: String , required :true, unique: true, match: /.+\@.+\..+/},
     password : {type: String , required :true},
     friends : {type:[{username : String, approved: Boolean}]},
});
[
  {
    "username": "ali",
    "email": "ali200@gmail,com",
    "password": "pdcjjfefmkadjakefkeofjafjafsfjsalnnryifajs",
    "friends": [
      {
        "id": "1",
        "username": "gamal",
        "approved": true
      },
      {
        "id": "2",
        "username": "osama",
        "approved": false
      },
      {
        "id": "3",
        "username": "john",
        "approved": true
      }
    ]
  }
]

我需要得到friends对象的数组,approved字段是true,如下所示

[
     {
        "id": "1",
        "username": "gamal",
        "approved": true
      },
      {
        "id": "3",
        "username": "john",
        "approved": true
      }

]

注解中的代码:

router.get("/getFriends", (req, res) => {
      var email = getEmailFromToken(req.header("Authorization"));
      User.findOne({
        email: email
      }).then((user) => res.status(200).send({
        friends: user.friends
      }));
li9yvcax

li9yvcax1#

通过使用代码,可以使用

User.findOne({ email: email }).then((user) => {
  const friends = user.friends.filter((f) => f.approved);
  res.status(200).send({ friends });
});

也可以使用查询

User.agregate([
  {
    $match: {
      email: "ali200@gmail.com",
    },
  },
  {
    $project: {
      _id: 1,
      friends: {
        $filter: {
          input: "$friends",
          as: "truelyFriend",
          cond: {
            $eq: ["$$truelyFriend.approved"],
          },
        },
      },
    },
  },
]).then((user) => {
  res.status(200).send({ friends: user[0].friends });
});

Mongo测试仪:mongo-playground

相关问题