【问题标题】:Mongoose plugin to assign extra data to a field but not saving to databaseMongoose 插件可将额外数据分配给字段但不保存到数据库
【发布时间】:2016-02-17 19:43:13
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否尝试过使用 [虚拟字段?] (mongoosejs.com/docs/2.7.x/docs/virtuals.html)
  • 刚刚添加了一个虚拟字段。但是我该如何设置标签呢? document.set('virtualTags', ['a', 'b', 'c']); 不工作。获取virtualTags: undefined
  • 刚刚想通了。工作中。谢谢@Manu
  • 你考虑过添加到你的插件schema.pre('save', function (next) { console.log("not persisting tags"); console.log(document); document.set('tags', null); next() })

标签: node.js mongodb mongoose


【解决方案1】:

这就是我使用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。在猫鼬中,所有以 __ 开头的内容都不会被持久化到数据库中。 然后

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

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

this.set('tags', tags);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2017-01-16
    • 2018-11-04
    • 1970-01-01
    • 2017-07-27
    • 2015-02-19
    相关资源
    最近更新 更多