[英]Applying getters on a "find" query in Mongoose?
Sorry if this has been asked before (I've searched, honestly).抱歉,如果之前有人问过这个问题(老实说,我已经搜索过了)。
Basically, I have a simple schema:基本上,我有一个简单的架构:
var ProductSchema = new Schema({
name: {type: String},
image: {type: String, get: getImageUrl},
stock: {type: Number},
price: {type: Number},
description: String
});
where在哪里
var getImageUrl = function(imgUrl) {
if (imgUrl.indexOf('http://') !== 0) {
return 'http://' + os.hostname() + (app.port ? app.port : '') + '/public/' + imgUrl;
} else {
return imgUrl;
}
};
The getter itself works, if I retrieve a specific item from the database, but not when I try to use Product.find()
or other queries, the getter doesn't get apply, and I get the "raw" (unprocessed) property. getter 本身有效,如果我从数据库中检索特定项目,但当我尝试使用
Product.find()
或其他查询时无效,getter 不会应用,并且我得到“原始”(未处理)属性. I've tried using Product.find({}, [], {getters: true}
to no avail. Am I missing something?我试过使用
Product.find({}, [], {getters: true}
无济于事。我错过了什么吗?
EDIT - using mongod version 1.8.5 and mongoose 2.5.10编辑 - 使用 mongod 1.8.5 版和 mongoose 2.5.10
Ran into this same issue today -- getters not being applied when using a find(). 今天遇到同样的问题-使用find()时不应用吸气剂。 My workaround was to use a virtual instead and include it in the json results.
我的解决方法是使用虚拟代替,并将其包含在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 });
Update your schema to add config for populating Object and JSON更新您的架构以添加用于填充对象和 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}
});
Reference: https://github.com/Automattic/mongoose/issues/2152参考: https : //github.com/Automattic/mongoose/issues/2152
The schema should be under definition of getter, if you define schema after getter function definition, you can reach it. 模式应该在getter的定义下,如果在getter函数定义之后定义模式,则可以到达它。 It should work according to the specification: http://mongoosejs.com/docs/getters-setters.html
它应该根据规范工作: http : //mongoosejs.com/docs/getters-setters.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.