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.

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.


You need to define your model schemas http://mongoosejs.com/docs/guide.html


Need Your Help

Laravel 4 migrate base table not found

php mysql laravel laravel-4

I'm trying to make following tutorial: https://medium.com/on-coding/e8d93c9ce0e2

Errors after updating to Xcode 8: "No such module" and "target overrides the `EMBEDDED_CONTENT_CONTAINS_SWIFT`build setting"

ios swift xcode cocoapods xcode8

I'm getting No such module for Pods when I try to build the project. If I remove the code expecting this Pod, another 'No such module' comes up for another Pod, which means every Pod must be affect...