如何转换.find()导致猫鼬?

发布于 2025-02-13 02:53:12 字数 679 浏览 1 评论 0原文

我在mongodb中使用用户收集了以下模式:

const User = mongoose.Schema({
  gender: {
    type: String
  },
  name: {
    type: String
  },
  location: {
    type: String
  },
  email: {
    type: String
  },
});

现在我需要从数据库中获取用户,但是以不同的架构(或格式),响应应该这样:

{
  "countries":
    [
      {
        "name": <country>,
         users: [
           {
             "name": <name>,
             "gender": <gender>,
             "email": <email>
           }
        ]
      }
    ]
}

我考虑使用<<代码> user.find()然后手动转换对象,但这是一个漫长的过程,我认为这可能会使我多次查询数据库,因此我想知道是否有一种方法可以获取数据我想要的方式直接的猫鼬。如果不是,您建议什么?

谢谢!

I have users collection in my MongoDB with the following schema:

const User = mongoose.Schema({
  gender: {
    type: String
  },
  name: {
    type: String
  },
  location: {
    type: String
  },
  email: {
    type: String
  },
});

Now I need to get the users from the database but in a different schema (or format), the response should like this:

{
  "countries":
    [
      {
        "name": <country>,
         users: [
           {
             "name": <name>,
             "gender": <gender>,
             "email": <email>
           }
        ]
      }
    ]
}

I thought of using User.find() then transform manually the object but It's a long process and i think it might make me query the database multiple times, so I would like to know if there is a way to get the data the way I want with Mongoose directly. If not what do you suggest?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悍妇囚夫 2025-02-20 02:53:12

您必须使用MongoDB加剧框架。
按国家 /地区分组,然后将用户推向数组。

db.collection.aggregate([
  {
    "$group": {
      "_id": "$location",
      "users": {
        "$push": {
          "name": "$name",
          "email": "$email",
          "gender": "$gender"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "name": "$_id",
      "users": 1
    }
  },
  {
    "$sort": {
      "name": 1
    }
  }
])

这是有效的示例:
https://mongoplayground.net/p/ri5h5jyozf8

You have to use Mongodb Aggragation Framework .
Group by country , then push users to array .

db.collection.aggregate([
  {
    "$group": {
      "_id": "$location",
      "users": {
        "$push": {
          "name": "$name",
          "email": "$email",
          "gender": "$gender"
        }
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "name": "$_id",
      "users": 1
    }
  },
  {
    "$sort": {
      "name": 1
    }
  }
])

Here is working example :
https://mongoplayground.net/p/RI5h5JYOZf8

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文