简体   繁体   中英

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. I've tried using Product.find({}, [], {getters: true} to no avail. Am I missing something?

EDIT - using mongod version 1.8.5 and mongoose 2.5.10

Ran into this same issue today -- getters not being applied when using a find(). My workaround was to use a virtual instead and include it in the json results.

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

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

The schema should be under definition of getter, if you define schema after getter function definition, you can reach it. It should work according to the specification: http://mongoosejs.com/docs/getters-setters.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM