Mongoose virtual fields included in toJSON by default: schemaOptions.toJSON.virtuals = true; still doesn't include virtual fields by default

两盒软妹~` 提交于 2019-12-03 06:23:08

问题


I saw in another answer that in order to include the virtual fields you must do like https://groups.google.com/forum/?fromgroups#!topic/mongoose-orm/HjrPAP_WXYs

var schemaOptions = {
  toJSON: {
    virtuals: true
  }
};

which I've done;

Now in the Schema:

 new Schema({...}, schemaOptions);

But still so, the data doesn't include the virtual.. :s

But like this works:

var docsCallback = function(err, docs){
    var i = docs.length;
    var nDocs = [];
    while(i--){
        nDocs[i] = docs[i].toObject({virtuals: true});
    }
    done(nDocs);
}

回答1:


Just tried:

  var schemaOptions = {
    toObject: {
      virtuals: true
    }
  };

and worked! ;)

Now by default I use:

  var schemaOptions = {
    toObject: {
      virtuals: true
    }
    ,toJSON: {
      virtuals: true
    }
  };



回答2:


You can do this way as well:

docs.set('toJSON', { virtuals: true });



回答3:


For me it worked only after adding getters: true to schema options, as mentioned in mongoose docs, i.e.

var schemaOptions = { toObject: { getters: true }, toJSON: { getters: true } };



来源:https://stackoverflow.com/questions/11557804/mongoose-virtual-fields-included-in-tojson-by-default-schemaoptions-tojson-virt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!