Mongoose插件,用于将额外数据分配给字段但不保存到数据库

时间:2016-02-17 07:47:09

标签: node.js mongodb mongoose

我正在尝试通过设置已保存到模型的字段tags来编写应该返回额外数据的插件,而不是将tags上的设置数据保存到数据库并返回。 这是插件代码。

module.exports = function samTagsPlugin(schema, options) {
    schema.post('init', function () {
        document.set('tags', ['a', 'b', 'c']);
    });
};

但是,tags字段会保存到mongodb,其值为['a', 'b', 'c']。有没有办法可以将动态值分配给tags而mongoose不会将提供的值保存到数据库中? 我使用的Mongoose版本是3.8.x

1 个答案:

答案 0 :(得分:0)

以下是我使用virtual字段解决此问题的方法(感谢@Manu)。

var MySchema = new Schema({
  type: {
    type: String,
    uiGrid: {name: 'Type', order: 15},
    required: true
  },
  contactNumber: {type: String, uiForm: {name: 'Contact Number'}},
  __customTags: [String]
}, {
  toObject: {
    virtuals: true
  },
  toJSON: {
    virtuals: true
  }
});

不是在这里我添加了一个字段 __customTags 。在mongoose中,所有以 __ 开头的内容都不会保留到数据库中。 然后

MySchema.virtual('tags').get(function() {
  return this.__customTags;
}).set(function(tags) {
  this.__customTags = tags;
});

从我的插件中,我将tags分配给我想要的值数组。

this.set('tags', tags);