node.js - Mongoose 插件将额外数据分配给字段但不保存到数据库

标签 node.js mongodb mongoose

我正在尝试编写一个插件,该插件应该通过设置已保存到模型的字段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 不会将提供的值保存到数据库中? 我使用的 Mongoose 版本是 3.8.x

最佳答案

这就是我如何使用虚拟字段解决这个问题(感谢@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;
});

在我的插件中,我将标签分配给我想要的值数组。

this.set('tags', tags);

关于node.js - Mongoose 插件将额外数据分配给字段但不保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35450686/

相关文章:

node.js - 是否可以在用户提供正确的详细信息后仅允许 vorpal 命令

node.js - 查询附近纬度/经度数据库的最佳方式?

node.js - 从外部url获取图片的url

javascript - 如何在node.js中访问整个应用程序中的数据库连接?

mongodb - Openshift Pod Storage Mongodb - 下载卷

json - 将 Json 文件导入 Mongoose

css - 如何输入属性作为 mixins 的参数

c# - MongoDB:C# 还是 JavaScript?

node.js - 使用Sinon 来 stub Mongoose 模型

javascript - 为什么不在回调中使用函数?