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

我有这个电话:

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);
  });
};

我在哪里指定要返回的属性?在文档中找不到。以上返回整个对象。我只希望返回几个属性。

这是我的架构:

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);

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

最佳答案

您使用投影。 mongoose query docs 中的第一个示例有一个投影操作。

注意:不是真正的代码 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.
})

没有指定 Person 架构,但我认为这个例子已经足够清楚了。

https://stackoverflow.com/questions/25330555/

相关文章:

javascript - Mongoose 连接到 MongoDB Atlas 的最佳池大小是多少?

javascript - MongoError : cannot change _id of a d

mongodb - 当父字段未知时,在嵌套文档中查找具有字段的记录

node.js - 聊天项目 - 使用 socket.io 进行负载平衡

performance - 字段类型在 MongoDB 索引中是否重要?

mongodb - Spark 流 : foreachRDD update my mongo RDD

mongodb - MongoDB批量FindAndModify的解决方案

mongodb - 更新 mongodb 中的嵌套文档

node.js - 将数据插入 MongoDB - 没有错误,没有插入

javascript - 在 MongoDB 中按字母顺序对文档进行排序(也称为自然排序顺序,人类排