Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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