我正在尝试编写一个插件,该插件应该通过设置已保存到模型的字段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/