programing

Mongoose.js: 항상 채우기 강제

starjava 2023. 6. 26. 20:46
반응형

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

반응형