猫鼬,查找,返回特定属性

Joe*_*Joe 15 mongoose mongodb node.js

我有这个电话:

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);
  });
};
Run Code Online (Sandbox Code Playgroud)

我在哪里指定要返回的属性?在文档中找不到它.以上返回整个对象.我只想要返回一些属性.

这是我的架构:

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);
Run Code Online (Sandbox Code Playgroud)

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

wdb*_*ley 23

你使用投影.mongoose查询文档中的第一个示例有一个隐藏的投影操作.

NB:不是真正的代码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.
})
Run Code Online (Sandbox Code Playgroud)

Person未指定架构,但我认为这个例子是很清楚.


mar*_*nho 18

MyModel.find({name: "john" }, 'name age address', function(err, docs) { })
Run Code Online (Sandbox Code Playgroud)

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


Has*_*war 15

猫鼬提供了多种项目与文件findfindOnefindById

1. 投影为字符串:

// INCLUDE SPECIFIC FIELDS
// find user and return only name and phone fields
User.findOne({ email: email }, 'name phone');

// EXCLUDE SPECIFIC FIELD
// find user and return all fields except password
User.findOne({ email: email }, '-password');
Run Code Online (Sandbox Code Playgroud)

2.通过projection属性进行投影:

// find user and return just _id field
User.findOne({ email: email }, {
  projection: { _id: 1 }
});
Run Code Online (Sandbox Code Playgroud)

三、使用.select方法:

// find user and return just _id and name field
User.findOne({ email: email }).select('name');

// find user and return all fields except _id
User.findOne({ email: email }).select({ _id: 0 });
Run Code Online (Sandbox Code Playgroud)

你也可以用findfindById方法做同样的事情。

  • Re (2) `{projection: {...}}` 部分似乎对我不起作用。如果我省略封装 `projection:` 字段并展平内容,它确实有效,如: `User.findOne({ email: email }, { _id: 1 })` (4认同)