gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:35 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com