node.js Mongoose,查找,返回特定属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25330555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:46:10  来源:igfitidea点击:

Mongoose, find, return specific properties

node.jsmongodbmongoose

提问by Joe

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.

我不希望在我的休息调用中包含 items 数组。

回答by wdberkeley

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

你使用投影。mongoose 查询文档中的第一个示例包含一个投影操作。

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

注意:不是真正的代码 b/c 我用三颗星突出了重要的部分

// 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 Personschema isn't specified but I think the example is clear enough.

Person方案没有规定,但我认为例子是再清楚不过。

回答by martinho

MyModel.find({name: "john" }, 'name age address', function(err, docs) { })

This will return fields name, age and address only.

这将仅返回字段名称、年龄和地址。

回答by monkeyinsight

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

您需要定义模型架构http://mongoosejs.com/docs/guide.html