codememo

Mongoose/Mongodb: 채워진 쿼리 데이터에서 필드 제외

tipmemo 2023. 6. 22. 21:53
반응형

Mongoose/Mongodb: 채워진 쿼리 데이터에서 필드 제외

저는 평균 환경에서 다음 몽구스 쿼리를 사용하여 특정 저자와 해당 책을 찾아 출력합니다.

Author
.findOne({personcode: code})
.select('-_id')
.select('-__v')
.populate('bookids') //referencing to book documents in another collection (->array of bookids)
.select('-_id') //this doens't affect the data coming from the bookids-documents
.select('-__v') //this doens't affect the data coming from the bookids-documents
.exec(function (err, data) {
   //foo
});

또한 외부 문서에서 입력되는 데이터에서 "_id" 및 "_v" 필드를 제외하고 싶습니다.어떻게 그것을 달성할 수 있습니까?

의 두 번째 매개 변수는 필드 선택 문자열이므로 다음과 같이 수행할 수 있습니다.

Author
  .findOne({personcode: code})
  .select('-_id -__v')
  .populate('bookids', '-_id -__v')
  .exec(function (err, data) {
    //foo
});

필드 선택 항목을 단일 문자열로 결합해야 합니다.

JohnnyHK에게 감사드리며 객체 매개 변수에 대해 다음과 같이 작동합니다.

Entity.populate({
    path: 'bookids',

    // some other properties
    match: {
        active: true
    },
    // some other properties

    select: '-_id -__v' // <-- this is the way
}).then(...) // etc

개별적으로 제외하기

User.findOne({_id: userId}).select("-password")

스키마 사용을 제외하려면 다음과 같이 하십시오.

var userSchema = mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
    select: false,
  },
});

아니면 이것도 효과가 있을 것입니다.

db.collection.find({},{"field_req" : 1,"field_exclude":0});

저는 조금 다른 것을 찾아 왔습니다.누군가 나와 같은 것을 필요로 할 경우를 대비해서요.

아래와 같이 스키마를 작성하는 동안 자동 검색할 특정 필드를 지정할 수 있습니다.

const randomSchema = mongoose.Schema({
  name: {type: String,trim: true},
  username: {type: String,trim: true},
  enemies: { 
    type: ObjectId, 
    ref: randomMongooseModel, 
    autopopulate:{
      select: '-password -randonSensitiveField' // remove listed fields from selection
    }
  },
  friends: { 
    type: ObjectId, 
    ref: randomMongooseModel, 
    autopopulate:{
      select: '_id name email username' // select only listed fields
    }
  }

});

이 예에서는 mongoose-autopulate 플러그인을 사용하고 있습니다.

언급URL : https://stackoverflow.com/questions/26915116/mongoose-mongodb-exclude-fields-from-populated-query-data

반응형