如何转换.find()导致猫鼬?
我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用MongoDB加剧框架。
按国家 /地区分组,然后将用户推向数组。
这是有效的示例:
https://mongoplayground.net/p/ri5h5jyozf8
You have to use Mongodb Aggragation Framework .
Group by country , then push users to array .
Here is working example :
https://mongoplayground.net/p/RI5h5JYOZf8