복붙노트

[MONGODB] 몽구스, 발견과 특정 필드를 선택

MONGODB

몽구스, 발견과 특정 필드를 선택

나는 만 특정 필드를 선택하려고 해요

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를 받고있어, 내 문서 스키마 만이 두 fiels, _id와 이름

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

왜???

해결법

  1. ==============================

    1.당신이 명시 적으로 제외하지 않는 한 _id 필드는 항상 존재합니다. 사용 그렇게 - 구문 :

    당신이 명시 적으로 제외하지 않는 한 _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);
        });
    };
    
  2. ==============================

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

    경우 당신이 스키마 필드의 대부분을 원하고 생략 할 몇 원하는, 당신은과 필드 이름을 앞에 수 있습니다 -. 두 번째 인수의 예 "-name"에 대한 반환 된 문서에서 이름 만 필드가됩니다 여기에 주어진 예 반면 문서에서 이름 필드에 포함되지 않습니다.

  3. ==============================

    3.몽구스의 기본 MongoDB의 코드를 사용하여 처리하는 더 좋은 방법이있다.

    몽구스의 기본 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/

    노트 :

    여기에 나열된 개체 목록 인쇄 / 반환되지 않습니다.

  4. ==============================

    4.DB 데이터

    DB 데이터

    [
      {
        "_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"
      }
    ]
    

    샘플 놀이터 작업

    링크

  5. ==============================

    5.이 작업을 수행하는 정확한 방법은 새로운 MongoDB를하고 nodejs 드라이버를 () 커서 방법의 .project 사용하는 것입니다.

    이 작업을 수행하는 정확한 방법은 새로운 MongoDB를하고 nodejs 드라이버를 () 커서 방법의 .project 사용하는 것입니다.

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

    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. from https://stackoverflow.com/questions/24348437/mongoose-select-a-specific-field-with-find by cc-by-sa and MIT license