gpt4 book ai didi

node.js - 如何使用 Mongoose 模式内部获取和设置函数

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

如何在模式创建中使用 if 条件, 我的架构是,

    var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var testSchema = new Schema({
"Name":String,
"TestValue":String
}, {
collection: 'test'
});

testSchema.eachPath(function(path) {
console.log(path);
});

testSchema.path('TestValue').set(function(value) {
console.log("value: " + value);
value="FFF";
this.TestValue = value;
return value;
});

module.exports = mongoose.model('test', testSchema);

我必须根据 if 条件更改 TestValue,如何解决问题...请给我一些解决方案来解决该问题。

最佳答案

这里有几个选项。这里有一些:

testSchema.path('TestValue').set(function(value) {
if (value === 'uh oh') {
return 'a different value';
} else {
return value;
}
});

或者,如果您愿意,也可以使用三元:

testSchema.path('TestValue').set(function(value) {
return (value === 'uh oh') ? 'a different value' : value
});

关于node.js - 如何使用 Mongoose 模式内部获取和设置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015078/

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