【问题标题】:Mongoose use of .select() method猫鼬使用 .select() 方法
【发布时间】:2012-03-21 20:02:36
【问题描述】:

我对@9​​87654321@ 方法的使用感到很困惑。我是这样用的,错了:

Transaction.find({username : user.username}).select('uniqueId', 'confirmation_link', 'item_name', 'timeout', 'username', function(err, txs){
        callback(txs);
});

我想要实现的只是从数据库中的事务中选择具有该用户名的事务,我只想取出select 方法中列出的字段。谁能指出我应该如何使用select 方法?谢谢。

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    docs 说你可以这样实现:

    猫鼬 v4.0

    // Retrieving only certain fields
    
    Model.find({}, 'first last', function (err, docs) {
    
    });
    

    过时的 API

    // Retrieving only certain fields
    
    Model.find({}, ['first', 'last'], function (err, docs) {
      // docs is an array of partially-`init`d documents
      // defaults are still applied and will be "populated"
    });
    

    所以您可以在没有select() 的情况下执行此操作。

    【讨论】:

    • 看来这种方法很有效,但在docs 中,我最终得到了我不想拥有的_id 之类的字段。
    • _id 之外的任何其他您不要求的字段?如果不是,我认为_id 是一个例外,因此总是返回......但这只是一个猜测
    • 实际上所有询问的字段都是除_id 字段之外的所有字段。我不想要它。有没有办法避免这种情况?
    • Mongo(不是 mongoose)自动返回 _id 进行查找,除非您明确告诉它不要这样做。在 mongo 中,您可以在投影中添加 _id: false 以不返回它,但我不知道这与 mongoose 中的(如果有的话)有什么关系。
    • 要排除 _id 字段,您可以将其添加到带有减号的选择字符串中,如下所示:Model.find({}, '-_id', function (err, docs)
    【解决方案2】:

    这是另一种方式:queries in mongoose

    Transaction.find({username : user.username})
    .select('uniqueId confirmation_link item_name timeout username')
    .exec(function(err, txs) {
            console.log(txs);
    });
    

    【讨论】:

    • 这很好用。如果你想排除一个字段,你可以这样做 .select("-field_I_dont_want")
    • 不适用于类型:对象字段passbase_webhook: { type: Object, select: false } 例如。 select(passbase_webhook.status) 在我的对象中,状态是关键`
    【解决方案3】:

    现在有一种更短的方法(不使用.select,不使用数组),只需将由空格分隔的字段作为第二个参数传递

    User.find({}, 'first last', function (err, usr) {
        //Got the result, saved a few bytes of code
    });
    

    The Docs

    【讨论】:

      【解决方案4】:

      要检索某些字段而不检索“_id”,您可以指定将其排除

      Model.find({}, {'Username':1, '_id':0}, function ( err, docs ){}.....
      

      【讨论】:

        【解决方案5】:

        select方法用于选择查询结果中要返回哪些字段,不包括select表示我们希望返回所有其他字段,这里按照文档的简单用法。

        // include a and b, exclude other fields  
        query.select('a b');
        
        // exclude c and d, include other fields  
        query.select('-c -d');
        

        更多信息,https://mongoosejs.com/docs/api.html#query_Query-select

        【讨论】:

          【解决方案6】:

          这很有帮助:How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

          看起来你有几个选择。

          1) 使用select('-_id')。 2) 使用find({whatever: values}, '-_id', callback...}。我无法验证此方法,但如果它适用于 select(),我不明白为什么它在这里不起作用。

          【讨论】:

            【解决方案7】:

            要仅检索特定字段,请使用以下命令,

            Model.find({/*Your query*/}, {'firstName':1, 'lastname':1, '_id':0}, //Notice, this will omit _id! function ( err, docs ){}.....

            这将起作用,并且不会引入任何额外的 id,例如 _id。

            【讨论】:

              【解决方案8】:

              在nodejs中可以通过这种方式轻松完成选择和投影操作。试试这个

                  var Selection={
                      <some key of data model > : <target value for that key field>,
                      <some key of data model > : <target value for that key field>
                      //you can add many parameters here selection operation
                      };
                  var Projection = {
                      __v    : false,
                      _id    : false
                      //you can add many parameters here for projection
                  };
                  <DataModel>.find(Selection,Projection,function (err,data) {
                      if(err){
                          console.log(err);
                      }else{
                       console.log(data);
                      }
                  });
              

              【讨论】:

                【解决方案9】:

                删除您要选择的字段之间的逗号和引号:

                Transaction.find({username : user.username}).select('uniqueId confirmation_link item_name timeout username', function(err, txs){
                    callback(txs);
                });
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2018-12-30
                  • 2012-09-01
                  • 2014-04-10
                  • 2021-04-16
                  • 1970-01-01
                  • 2021-10-10
                  • 2019-03-25
                  • 2018-03-19
                  相关资源
                  最近更新 更多