我正在尝试通过设置已保存到模型的字段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
。
答案 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);