有沒有辦法存盤檔案,然后在以后獲取它的更新值,而無需再次查詢和填充?
const someDocument = await SomeModel.findOne({...}).populate(...);
// store a reference to it for use
const props = {
document: someDocument,
...
}
// at a later time
await props.document.getLatest() <-- update and populate in place?
uj5u.com熱心網友回復:
如此處所述,您可以通過在模式級別添加函式來定義自己的自定義檔案實體方法。
取自貓鼬檔案的示例:
// define a schema
const animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return mongoose.model('Animal').find({ type: this.type }, cb);
};
const Animal = mongoose.model('Animal', animalSchema);
const dog = new Animal({ type: 'dog' });
dog.findSimilarTypes((err, dogs) => {
console.log(dogs); // woof
});
這是我能想到的唯一方法 - 添加一個填充的函式。
另一件事可能會有所幫助:您可以在“查找”上創建一個預掛鉤并在其中添加填充
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432403.html
標籤:javascript 猫鼬
