[英]Applying getters on a "find" query in Mongoose?
抱歉,如果之前有人問過這個問題(老實說,我已經搜索過了)。
基本上,我有一個簡單的架構:
var ProductSchema = new Schema({
name: {type: String},
image: {type: String, get: getImageUrl},
stock: {type: Number},
price: {type: Number},
description: String
});
在哪里
var getImageUrl = function(imgUrl) {
if (imgUrl.indexOf('http://') !== 0) {
return 'http://' + os.hostname() + (app.port ? app.port : '') + '/public/' + imgUrl;
} else {
return imgUrl;
}
};
getter 本身有效,如果我從數據庫中檢索特定項目,但當我嘗試使用Product.find()
或其他查詢時無效,getter 不會應用,並且我得到“原始”(未處理)屬性. 我試過使用Product.find({}, [], {getters: true}
無濟於事。我錯過了什么嗎?
編輯 - 使用 mongod 1.8.5 版和 mongoose 2.5.10
今天遇到同樣的問題-使用find()時不應用吸氣劑。 我的解決方法是使用虛擬代替,並將其包含在json結果中。
schema.virtual("APP_ID_URL").get(function() {
if (this.APP_ID > 0){
return "<a href='#'>" + this.APP_ID + "</a>";
}
else{
return "";
}
});
schema.set('toJSON', { virtuals: true });
更新您的架構以添加用於填充對象和 JSON 的配置
var ProductSchema = new Schema({
name: {type: String},
image: {type: String, get: getImageUrl},
stock: {type: Number},
price: {type: Number},
description: String
},
{
toObject : {getters: true},
toJSON : {getters: true}
});
模式應該在getter的定義下,如果在getter函數定義之后定義模式,則可以到達它。 它應該根據規范工作: http : //mongoosejs.com/docs/getters-setters.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.