Home > Blockchain >  I am looking to list my mongodb collection data by a specific field
I am looking to list my mongodb collection data by a specific field

Time:11-14

I am looking to create a list from my mongodb database that will be mapped by a specific field the "username" field.

I read on here it is not wise to allocate a collection per user to do namespaceing limits with mongodb so I am trying to sort my collection per username field

My JSON object looks like this

Collection "users"

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

this is my Next.js page file

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 } }
}

the resulting data looks like this

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

how can i sort this data so that it only shows user01's data and not the other users? I need it to look like this

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

Any help on this would be awesome... thanks in advance.

CodePudding user response:

Change the find(...) to accept the desired filter.

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