简体   繁体   English

Mongoose .select() 方法的使用

[英]Mongoose use of .select() method

I'm pretty confused with the use of the select method.我对select方法的使用感到很困惑。 This is how I use it, and it's wrong:我是这样用的,错了:

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

What I'm trying to achieve is simply to select from the transactions in the database the ones with that username and I want to take out just the fields listed in the select method.我想要实现的只是从数据库中的事务中使用该用户名的事务到 select,我只想取出select方法中列出的字段。 Can anyone point out how should I use the select method?谁能指出我应该如何使用select方法? Thanks.谢谢。

the docs say you can achieve this like so:文档说你可以这样实现:

Mongoose v4.0猫鼬 v4.0

// Retrieving only certain fields

Model.find({}, 'first last', function (err, docs) {

});

old outdated API旧的过时 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"
});

so you can do this without select() .所以你可以在没有select()的情况下做到这一点。

this is another way: queries in mongoose这是另一种方式: mongoose 中的查询

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

Now there is a shorter way of doing this (not using .select and not using an array), just passing the fields separate by spaces as the second argument现在有一种更短的方法(不使用.select也不使用数组),只需将由空格分隔的字段作为第二个参数传递

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

The Docs文档

Select method is used to select which fields are to be returned in the query result, excluding select means we want all the other fields to be returned, here is simple usage as per the docs. select 方法用于选择查询结果中要返回哪些字段,不包括 select 表示我们希望返回所有其他字段,这里按照文档的简单用法。

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

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

More information here, https://mongoosejs.com/docs/api.html#query_Query-select更多信息在这里, https://mongoosejs.com/docs/api.html#query_Query-select

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

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

This was pretty helpful: How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?这很有帮助: 如何保护 Mongoose/MongoDB 中的密码字段,以便在我填充集合时它不会在查询中返回?

Looks like you have a few options.看起来你有几个选择。

1) Use select('-_id') . 1) 使用select('-_id') 2) Use find({whatever: values}, '-_id', callback...} . I can't verify this method, but if it works with select() , I don't see why it wouldn't work here. 2) 使用find({whatever: values}, '-_id', callback...} 。我无法验证此方法,但如果它与select()一起使用,我不明白为什么它不起作用这里。

To retrieve specific fields only, use the following,要仅检索特定字段,请使用以下命令,

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

that will work and will NOT bring in any extra id such as _id.这将起作用并且不会带来任何额外的ID,例如_id。

selection & projection operation can be done in this way easyly in nodejs.在 nodejs 中可以通过这种方式轻松完成选择和投影操作。 Try this尝试这个

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

这种语法也适用

Transaction.find({username : user.username}).select(['uniqueId', 'confirmation_link', 'item_name', 'timeout', 'username']);

Remove the commas and quotes between the fields you want to select:删除要选择的字段之间的逗号和引号:

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

set select: false for the fields that you want to exclude in your Schema on server request.select: false设置为要根据服务器请求在Schema中排除的字段。

example例子

const userSchema = mongoose.Schema({
    name: {
        type: String,
        select: false
    },

    password: {
        type: Number,
        select: false

    }
})

that way the only fields that you want coming in should be the ones without select: false这样,您想要进入的唯一字段应该是没有select: false

If for some reason you need to get the password(any field) but need to have select: false in the schema.如果出于某种原因您需要获取密码(任何字段)但需要在模式中包含select: false use select('+password etc')使用select('+password etc')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM