문서에서 일부 필드를 제외하는 방법
다음과 같은 간단한 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.
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
'developer tip' 카테고리의 다른 글
외부를 클릭하여 jquery 드롭 다운 메뉴 닫기 (0) | 2021.01.05 |
---|---|
문자열에서 ASCII가 아닌 문자 제거 (0) | 2021.01.05 |
첫 번째 명령 이후에 종료하지 않고 배치 파일에서 여러 git 명령을 실행하려면 어떻게해야합니까? (0) | 2020.12.31 |
앱으로 돌아갈 때 정적 변수 null (0) | 2020.12.31 |
Nuget repositories.config 파일은 무엇입니까? (0) | 2020.12.31 |