Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

node.js - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...