mongoose 我希望按特定字段列出我的mongodb收集数据

0pizxfdo  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(143)

我正在寻找从我的mongodb数据库创建一个列表,将由一个特定的字段Map“用户名”字段。
我在这里读到,为每个用户分配一个集合来使用mongodb进行名称空间限制是不明智的,所以我尝试按用户名字段对集合进行排序
我的JSON对象如下所示
“用户”集合

{
    "_id": {
        "$oid": "636a904602fa5ea137276767"
    },
    "project_name": "project01",
    "username": "user01",
    "__v": {
        "$numberInt": "0"
    }
}

这是我的Next.js页面文件

import dbConnect from '../../lib/dbConnect'
import User from '../models/User'

export default function Page({ users }) {
    return (
        <>
            {users.map((user) => (
                <div key={user._id}>
                    <span>username: {user.username} project_name: {user.project_name}</span>
                </div>
            ))}
        </>
    );
}

export async function getServerSideProps() {

    await dbConnect()

    const result = await User.find({})
    const users = result.map((doc) => {
        const user = doc.toObject()
        user._id = user._id.toString()
        return user
    })

    return { props: { users: users } }
}

生成的数据如下所示

username: user01 project_name: project01
username: user02 project_name: project02
username: user01 project_name: project03
username: user03 project_name: project04
username: user02 project_name: project05
username: user03 project_name: project06
username: user02 project_name: project07
username: user02 project_name: project08
username: user02 project_name: project09
username: user01 project_name: project10

如何对这些数据进行排序,使其只显示user01的数据而不显示其他用户的数据?

username: user01 project_name: project01
username: user01 project_name: project03
username: user01 project_name: project10

任何帮助这将是可怕的...提前感谢。

qnyhuwrf

qnyhuwrf1#

更改find(...)以接受所需的滤波器。

const specificUserName = 'user01' // Set this wherever
const result = await User.find({ username: specificUserName })

相关问题