Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, find, return specific properties

I have this get call:

exports.getBIMFromProject = function(req, res){   mongoose.model('bim').find({projectId: req.params['prj_id']}, function(err, bim){     if(err){       console.error(err);       res.send(500)     }     res.send(200, bim);   }); }; 

Where do I specify which properties I want to return? Can't find it in the docs. The above returns the entire object. I only want a few properties returned.

This is my schema:

var mongoose = require('mongoose'),   Schema = mongoose.Schema;  var bimSchema = new Schema({   projectId: Number,   user: String,   items:[     {       bimObjectId: Number,       typeId: String,       position:{         floor: String,         room:{           name: String,           number: String         }       }     }   ] });  mongoose.model('bim', bimSchema); 

I don't want the items array included in my rest call.

like image 298
Joe Avatar asked Aug 15 '14 16:08

Joe


People also ask

What does find () return in Mongoose?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

What is $in in Mongoose?

The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.

How do you use Mongoose findOne?

Mongoose | findOne() FunctionThe findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition. Installation of mongoose module: You can visit the link to Install mongoose module.

What is __ V in MongoDB?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.


1 Answers

You use projection. The first example in the mongoose query docs has a projection operation tucked in.

NB: not real code b/c I highlighted the important bits with triple stars

// find each person with a last name matching 'Ghost', ***selecting the `name` and `occupation` fields*** Person.findOne({ 'name.last': 'Ghost' }, ***'name occupation'***, function (err, person) {   if (err) return handleError(err);   console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host. }) 

The Person schema isn't specified but I think the example is clear enough.

like image 124
wdberkeley Avatar answered Sep 23 '22 07:09

wdberkeley