Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Damian Wynter
Damian Wynter
15,803 Points

mongoose find statement

Hello all, i am trying to get all the faculties in the university schema below:

let universitySchema = new Schema({ name: String, description: String, faculties: [facultySchema], universityBuildings: [universityBuildingsSchema], students: [userSchema], banks: [bankSchema], atms: [atmSchema], foods: [foodSchema], icon: String });

let University = Mongoose.model('University', universitySchema);

using the University Object, how would i get the results of all the faculties only?

What i currently have:

// Get /faculties // Route to get all faculties router.get('/university/:uID/faculties', (req, res, next) => { // Return all faculties University.find({}, null, (error, faculty) => { if(error) return next(error); res.json(faculty); }) });

The above code returns the university document i know, just need help getting only faculties.

Thanks in advance guys.

To start, learn how to submit code in a proper format :)

2 Answers

Lucas Santos
Lucas Santos
19,315 Points
University.find({}).select({faculties: 1, _id: 0});
Damian Wynter
Damian Wynter
15,803 Points

Thank you Lucas however that doesn't seem to work for me. Maybe i am doing something wrong, i am trying to create a REST API where persons request the faculties and the faculties is sent back to the client. How would i convert the code below to achieve that. when i add the select method i get an error stating select statements accept only one argument. however i want to use a callback function to handle the response.

router.get('/university/:uID/faculties', (req, res, next) => {
   // Return all faculties
   University.find({}, null, (error, faculty) => {
       if(error) return next(error);
       res.json(faculty);
   });
});
Damian Wynter
Damian Wynter
15,803 Points

Solved it, Thanks though