【问题标题】:Mongoose, Select a specific field with findMongoose,使用查找选择特定字段
【发布时间】:2014-08-12 11:03:57
【问题描述】:

我正在尝试仅选择一个特定字段

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

但是在我的 json 响应中,我也收到了 _id,我的文档架构只有两个字段,_id 和 name

[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]

为什么???

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    _id 字段始终存在,除非您明确排除它。使用- 语法这样做:

    exports.someValue = function(req, res, next) {
        //query with mongoose
        var query = dbSchemas.SomeValue.find({}).select('name -_id');
    
        query.exec(function (err, someValue) {
            if (err) return next(err);
            res.send(someValue);
        });
    };
    

    或通过对象显式:

    exports.someValue = function(req, res, next) {
        //query with mongoose
        var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});
    
        query.exec(function (err, someValue) {
            if (err) return next(err);
            res.send(someValue);
        });
    };
    

    【讨论】:

    • 我认为.select 只是在你得到所有这些之后选择字段的过滤器,我的建议是使用.find({}, 'name -_id')
    • @Hongarc .find({}, 'name -_id') 似乎不起作用?
    • 有没有一种方法可以直接获取值,而无需像 [ 'value1', 'value2', 'value3' ] 这样的 obj 而不是 [ 'name':'value1', 'name': “值2”,“名称”:“值3”]
    • 我在使用它时遇到错误,因为显然我不能混合使用包含和拒绝。我想我应该将其作为参数传递给 .select() 仅此 id 以排除它:.select({ "_id":0 })
    【解决方案2】:

    现在有一种更短的方法:

    exports.someValue = function(req, res, next) {
        //query with mongoose
        dbSchemas.SomeValue.find({}, 'name', function(err, someValue){
          if(err) return next(err);
          res.send(someValue);
        });
        //this eliminates the .select() and .exec() methods
    };
    

    如果您想要大部分 Schema fields 并且只想省略一些,您可以在字段 name 前加上 -(减号)。例如,第二个参数中的 "-name"not 在文档中包含 name 字段,而此处给出的示例将具有 only 返回文档中的 name 字段。

    【讨论】:

    • 对于那些想要过滤多个字段的人,不要用逗号分隔它们,只需纯空格:blogItemModel.find({}, 'title intro_image intro_text publish_date', function(err, blog_items){..
    • 对于那些想要在上面使用 where 子句的人 dbSchema.Somevalue.find({userEmail:'test@test.com'},'userEmail -_id', function(err, someValue )
    • 多个字段将是 ['name', 'field2', 'field3', 'etc'] 而不仅仅是 'name'
    【解决方案3】:

    在 Mongoose 中使用本机 MongoDB 代码可以更好地处理它。

    exports.getUsers = function(req, res, next) {
    
        var usersProjection = { 
            __v: false,
            _id: false
        };
    
        User.find({}, usersProjection, function (err, users) {
            if (err) return next(err);
            res.json(users);
        });    
    }
    

    http://docs.mongodb.org/manual/reference/method/db.collection.find/

    注意:

    var usersProjection

    此处列出的对象列表将不会被返回/打印。

    【讨论】:

    • 你如何使用 findOne 做到这一点?
    • 问卷需要名称 json 数组。使用您的方法,其他关键就在那里,而不是像年龄等一样
    • 太棒了,正是我想要的
    【解决方案4】:

    数据库数据

    [
      {
        "_id": "70001",
        "name": "peter"
      },
      {
        "_id": "70002",
        "name": "john"
      },
      {
        "_id": "70003",
        "name": "joseph"
      }
    ]
    

    查询

    db.collection.find({},
    {
      "_id": 0,
      "name": 1
    }).exec((Result)=>{
        console.log(Result);
    })
    

    输出:

    [
      {
        "name": "peter"
      },
      {
        "name": "john"
      },
      {
        "name": "joseph"
      }
    ]
    

    工作示例游乐场

    link

    【讨论】:

      【解决方案5】:

      执行此操作的确切方法是将.project() 光标方法与新的mongodbnodejs 驱动程序一起使用。

      var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })
      

      【讨论】:

      • .project() 仅适用于聚合。如果你想在 find({},{ name: 1, _id: 0 }) 方法中使用 find 使用第二个参数。
      • 不使用新的 mongodb 节点驱动程序,您必须使用这种方式。但是对于猫鼬,您可以使用第二个参数。
      • 啊,在nodejs驱动里面。
      • 不明白为什么,但是在新版本中@Anthony 是对的...低版本你可以这样做...非常混乱
      【解决方案6】:

      排除

      以下代码将检索每个文档中除密码以外的所有字段:

      const users = await UserModel.find({}, {
        password: 0 
      });
      console.log(users);
      

      输出

      [
        {
          "_id": "5dd3fb12b40da214026e0658",
          "email": "example@example.com"
        }
      ]
      

      包括

      以下代码将仅检索每个文档中的电子邮件字段:

      const users = await UserModel.find({}, {
        email: 1
      });
      console.log(users);
      

      输出

      [
        {
          "email": "example@example.com"
        }
      ]
      

      【讨论】:

        【解决方案7】:

        提示:0 表示忽略,1 表示显示。

        示例 1:

        User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
        

        示例 2:

        User.findById(id).select("_id, isActive").then(...)
        

        示例 3:

        User.findById(id).select({ _id: 1, isActive: 1, name: 1, createdAt: 0 }).then(...)
        

        【讨论】:

        • 最适合安全的解决方案,无需任何附加功能!
        • 看来你不能再包含 0 和 1 的混合
        【解决方案8】:

        我在 mongoose 中找到了一个非常好的选择,它使用 distinct 返回文档中所有特定字段的数组。

        User.find({}).distinct('email').then((err, emails) => { // do something })

        【讨论】:

          猜你喜欢
          • 2021-08-16
          • 2014-10-14
          • 1970-01-01
          • 2013-01-09
          • 1970-01-01
          • 2020-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多