developer tip

문서에서 일부 필드를 제외하는 방법

optionbox 2021. 1. 5. 07:57
반응형

문서에서 일부 필드를 제외하는 방법


다음과 같은 간단한 shema가 있습니다.

 var userSchema = new Schema({
    name : String,
   age: Number,
   _creator: Schema.ObjectId
  });

  var User = mongoose.model('User',userSchema);

내가 원하는 것은 새 문서를 만들고 클라이언트로 돌아가는 것입니다. 그러나 하나에서 'creator'필드를 제외하고 싶습니다.

app.post('/example.json', function (req, res) {
   var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
   user.save(function (err) {
      if (err) throw err;

      res.json(200, {user: user});     // how to exclude the _creator field?
   });
});

마지막에 _creator 필드없이 새로 생성 된 사용자를 보내고 싶습니다.

{
   name: 'John',
   age: 45
} 

몽구스에 대한 추가 찾기 요청없이 만들 수 있습니까?

추신 : 그것을 만드는 것이 바람직합니다


스키마 수준에서이를 처리하는 또 다른 방법은 모델의 toJSON을 재정의하는 것입니다.

UserSchema.methods.toJSON = function() {
  var obj = this.toObject()
  delete obj.passwordHash
  return obj
}

클라이언트에 제공 한 json에서 암호 해시를 제외하는 방법을 찾고있는이 질문 select: false을 발견했고 데이터베이스에서 값을 전혀 검색하지 않았기 때문에 verifyPassword 함수가 손상되었습니다.


문서화 된 방법은

UserSchema.set('toJSON', {
    transform: function(doc, ret, options) {
        delete ret.password;
        return ret;
    }
});

업데이트-화이트리스트를 사용할 수 있습니다.

UserSchema.set('toJSON', {
    transform: function(doc, ret, options) {
        var retJson = {
            email: ret.email,
            registered: ret.registered,
            modified: ret.modified
        };
        return retJson;
    }
});

pymongo에서 비슷한 답변을 찾으려고 할 때 질문을 보았습니다. mongo 셸에서 find () 함수 호출을 사용하면 결과 문서가 어떻게 보이는지 지정하는 두 번째 매개 변수를 전달할 수 있습니다. 속성 값이 0 인 사전을 전달하면이 쿼리에서 나오는 모든 문서에서이 필드를 제외하게됩니다.

예를 들어 귀하의 경우 쿼리는 다음과 같습니다.

db.user.find({an_attr: a_value}, {_creator: 0});

_creator 매개 변수는 제외됩니다.

pymongo에서 find () 함수는 거의 동일합니다. 그래도 몽구스로 어떻게 번역되는지 잘 모르겠습니다. 나중에 수동으로 필드를 삭제하는 것보다 더 나은 솔루션이라고 생각합니다.

도움이 되었기를 바랍니다.


toObject()문서를 호출 하여 자유롭게 수정할 수있는 일반 JS 객체로 변환 할 수 있습니다.

user = user.toObject();
delete user._creator;
res.json(200, {user: user});

lodash 유틸리티 .pick () 또는.omit()

var _ = require('lodash');

app.post('/example.json', function (req, res) {
    var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
    user.save(function (err) {
        if (err) throw err;
        // Only get name and age properties
        var userFiltered = _.pick(user.toObject(), ['name', 'age']);
        res.json(200, {user: user});
    });
});

The other example would be:

var _ = require('lodash');

app.post('/example.json', function (req, res) {
    var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
    user.save(function (err) {
        if (err) throw err;
        // Remove _creator property
        var userFiltered = _.omit(user.toObject(), ['_creator']);
        res.json(200, {user: user});
    });
});

By following the MongoDB documentation, you can exclude fields by passing a second parameter to your query like:

User.find({_id: req.user.id}, {password: 0})
        .then(users => {
          res.status(STATUS_OK).json(users);
        })
        .catch(error => res.status(STATUS_NOT_FOUND).json({error: error}));

In this case, password will be excluded from the query.

font: https://docs.mongodb.com/v2.8/tutorial/project-fields-from-query-results/#return-all-but-the-excluded-field


I am using Mongoosemask and am very happy with it.

It does support hiding and exposing properties with other names based on your need

https://github.com/mccormicka/mongoosemask

var maskedModel = mongomask.mask(model, ['name', 'age']); //And you are done.

ReferenceURL : https://stackoverflow.com/questions/11160955/how-to-exclude-some-fields-from-the-document

반응형