반응형
Mongoose.js: 항상 채우기 강제
모델에게 항상 특정 필드를 채우도록 지시하는 방법이 있습니까?
찾기 쿼리에 "필드"를 채우는 것과 같은 것입니다.
{field: Schema.ObjectId, ref: 'Ref', populate: true}
?
Mongoose 4.0에서는 Query Hooks를 사용하여 원하는 항목을 자동으로 채울 수 있습니다.
아래 예시는 발레리 카르포프의 소개 문서에서 나온 것입니다.
스키마의 정의:
var personSchema = new mongoose.Schema({
name: String
});
var bandSchema = new mongoose.Schema({
name: String,
lead: { type: mongoose.Schema.Types.ObjectId, ref: 'person' }
});
var Person = mongoose.model('person', personSchema, 'people');
var Band = mongoose.model('band', bandSchema, 'bands');
var axl = new Person({ name: 'Axl Rose' });
var gnr = new Band({ name: "Guns N' Roses", lead: axl._id });
자동 채우기 쿼리 후크:
var autoPopulateLead = function(next) {
this.populate('lead');
next();
};
bandSchema.
pre('findOne', autoPopulateLead).
pre('find', autoPopulateLead);
var Band = mongoose.model('band', bandSchema, 'bands');
이 플러그인은 다음 질문에 대한 해결책입니다.
https://www.npmjs.com/package/mongoose-autopopulate
쿼리 후크를 사용하여 자동 채우기를 수행하지만 다음과(와) 함께 작동하지 않습니다.create()
그리고.save()
수정된 필드의 경우.내 코드는 다음과 같습니다.
var autoPopulate = function(next) {
this.populate('updated_by','name').populate('created_by','name');
next();
};
ProjectSchema.pre('findOne', autoPopulate);
ProjectSchema.pre('find', autoPopulate);
업데이트하는 경우Project
오직.created_by
입력됨
새 항목을 작성하는 경우Project
둘다요.created_by
그리고.updated_by
입력되지 않았습니다.
find
그리고.findOne
문제없이 작동합니다.
항상 두 항목을 채우려면 어떻게 해야 합니까?created_by
그리고.updated_by
?
언급URL : https://stackoverflow.com/questions/21592351/mongoose-js-force-always-populate
반응형
'programing' 카테고리의 다른 글
CALayers는 UIView의 경계 변경에 대해 크기를 조정하지 않았습니다. 왜죠? (0) | 2023.06.26 |
---|---|
그룹화된 데이터에서 첫 번째 행과 마지막 행 선택 (0) | 2023.06.26 |
오류: 다음 파일에 대한 로컬 변경 내용은 체크아웃 시 덮어씁니다. (0) | 2023.06.26 |
Oracle 시퀀스 트랜잭션 기능 (0) | 2023.06.26 |
개체의 메모리 사용량을 확인하시겠습니까? (0) | 2023.06.26 |