How to search for key value pairs in Mongoose and MongoDB

Viewed 48

I am creating a MERN app that allows users to enter in their level of coding knowledge to the database.

There is a value called skills in the Schema that allows this:

skills: [{
    skill: String,
    yearsExperience: String
}]

This means a user's skills will look like this in the MongoDB database:

skills: [
    {skill: 'React', yearsExperience: '3 years'},
    {skill: 'HTML', yearsExperience: '5 years'},
    {skill: 'JavaScript', yearsExperience: '5 years'},
    {skill: 'Git', yearsExperience: '3 years'},
    {skill: 'TypeScript', yearsExperience: '< 1 year'},
    {skill: 'C++', yearsExperience: '1 years'}
]

I am creating an admin panel that I want to be able to query every user's skills to find suitable matches. So if I want to find someone that has at-least 2 years of React experience along with at-least one year of C++ experience, this query would respond with a JSON object containing all users that meet this requirement. This issue is I have never worked with these dynamic objects being saved to the database so I am not sure if Mongoose has a built in method of dealing with this or not. Any suggestions would be great!

1 Answers

Because years of experience is a metric that you want to sort and filter on, you really don't want to store that as a string. You should store it as a number if that's something under your control, at which point you can perform a very simple find using operators like $gt.

Related