[javascript] 몽구스, 찾기로 특정 필드 선택

특정 필드 만 선택하려고합니다.

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와 이름이라는 두 개의 파일 만 있습니다.

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

왜???



답변

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


답변

이제 더 짧은 방법이 있습니다.

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"를 들어 두 번째 인수의 경우 문서에 필드가 포함 되지 않지만name 여기에 제공된 예제 에는 반환 된 문서 의 필드 name 있습니다.


답변

Mongoose의 Native 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

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


답변

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"
  }
]

작업 샘플 놀이터

링크


답변

들어오지 못하게 하다

아래 코드는 각 문서 내에서 비밀번호를 제외한 모든 필드를 검색합니다.

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"
  }
]


답변

이를 수행하는 정확한 방법 .project()은 new mongodbnodejsdriver 에서 커서 방법 을 사용 하는 것입니다 .

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


답변

예를 들면

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

0은 무시를 의미합니다.

1은 표시를 의미합니다.