programing

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

linuxpc 2023. 3. 12. 10:32
반응형

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

저는 다음과 같은 간단한 셰마를 가지고 있습니다.

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

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

새 문서를 만들고 클라이언트로 돌아가지만 다음 중 하나에서 '작성자' 필드를 제외합니다.

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
} 

mongoose에 추가 find 요청 없이 만들 수 있나요?

추신: 다음 날짜까지 작성하는 것이 좋습니다.

스키마 수준에서 이를 처리하는 또 다른 방법은 J로 덮어쓰는 것입니다.모델의 SON.

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

할 방법을 이을 하게 .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;
    }
});

내가 피몽고와 비슷한 답을 찾으려고 했을 때 너의 질문을 떠올려봐.mongo 쉘에서는 find() 함수 호출을 사용하여 결과 문서의 모양을 지정하는 두 번째 파라미터를 전달할 수 있습니다.속성 값이 0인 사전을 전달하면 이 질의에서 나오는 모든 문서에서 이 필드를 제외하게 됩니다.

예를 들어, 이 경우 쿼리는 다음과 같습니다.

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

_creator 파라미터는 제외됩니다.

pymongo에서 find() 함수는 거의 동일합니다.몽구스로 어떻게 해석될지는 모르겠지만.나중에 필드를 수동으로 삭제하는 것보다 더 나은 해결책이라고 생각합니다.

도움이 됐으면 좋겠다.

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

다른 예는 다음과 같습니다.

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

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

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

MongoDB 설명서에 따라 다음과 같은 두 번째 매개 변수를 쿼리에 전달하여 필드를 제외할 수 있습니다.

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

이 경우 비밀번호는 쿼리에서 제외됩니다.

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

나는 몽구스마스크를 쓰고 있는데 매우 행복하다.

필요에 따라 다른 이름으로 속성을 숨기거나 노출할 수 있습니다.

https://github.com/mccormicka/mongoosemask

var maskedModel = mongomask.mask(model, ['name', 'age'); //완료되었습니다.

스키마 파일 자체에서 이 작업을 수행할 수 있습니다.

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

userSchema.statics.toClientObject = function (user) {
  const userObject = user?.toObject();
  // Include fields that you want to send
  const clientObject = {
    name: userObject.name,
    age: userObject.age,
  };

  return clientObject;
};

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

다음으로 클라이언트에 응답하는 컨트롤러 방식에서 다음 절차를 수행합니다.

return res.json({
    user: User.toClientObject(YOUR_ENTIRE_USER_DOC),
  });

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

반응형