【问题标题】:Mongoose, find, return specific propertiesMongoose,查找,返回特定属性
【发布时间】:2014-10-09 10:23:58
【问题描述】:

我有这个电话:

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 数组。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您使用投影。 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 架构没有指定,但我认为这个例子已经很清楚了。

    【讨论】:

      【解决方案2】:
      MyModel.find({name: "john" }, 'name age address', function(err, docs) {
          console.log(docs);
      });
      

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

      【讨论】:

        【解决方案3】:

        .Select()方法用于选择查询结果中要返回哪些字段

        let result = await MyModel.find({ user : "user" }).select('name lastname status')
        

        【讨论】:

          【解决方案4】:

          .select() 的帮助下,这是可能的。

          • 如果所需的字段数少于总字段数,那么, .select('projectId user')可以使用
          • 否则,要忽略的字段数比总字段数少, 可以使用.select('-items')

          所以对于获取一个字段,简单地说,可以传递空格分隔的字段字符串,而对于忽略该字段,可以使用该字段之前用“-”分隔的空格字符串。

          对于more documentation

          【讨论】:

            【解决方案5】:

            Mongoose 提供多种方式来投影文档,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');
            

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

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

            3.使用.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 });
            

            您也可以对 findfindById 方法执行相同的操作。

            【讨论】:

            • Re (2) {projection: {...}} 部分似乎对我不起作用。如果我省略封装 projection: 字段并展平内容,它确实有效,如:User.findOne({ email: email }, { _id: 1 })
            猜你喜欢
            • 2022-10-19
            • 2020-08-22
            • 1970-01-01
            • 2022-06-14
            • 2019-08-16
            • 2011-08-11
            • 1970-01-01
            • 2021-12-25
            • 2016-01-04
            相关资源
            最近更新 更多