【发布时间】:2015-01-03 06:45:36
【问题描述】:
我在 JavaScript (Express.js/Mongoose) 中有这样一个 JSON:
// create a document
var demo = new DemoSchema({
hat: { money: "500" },
functions: {
func1: "this.hat.money - (0.02*this.hat.money)"
}
});
现在我想将此字符串用作对象。能实现吗?
例如
DemoSchema.virtual('hat.newValue').get(function() {
return this.functions.func1;
});
console.log('%s is 2% less', demo.hat.newValue);
// above prints: this.hat.money - (0.02*this.hat.money is 2% less)
更多关于为什么要这样做的背景信息: https://groups.google.com/forum/#!topic/mongoose-users/lzyjg0b8Vn0
【问题讨论】:
-
为什么你的函数是字符串而不是函数?我会成功的:
func1: function() {this.hat.money - (0.02*this.hat.money) } -
有趣,但有两个问题:如何执行该功能以及是否可以在 demo.functions.func1 中更改此类功能?
-
我不知道 Express 或 Mongoose 是如何工作的,所以我不能确切地告诉你,但你调用它就像你调用任何其他函数一样:
console.log('%s is 2% less', demo.hat.newValue());而你将无法编辑函数内部的内容,但您始终可以将 func1 重置为新函数。 -
我明白了。我尝试了这个建议,但即使将其定义为函数,它也会像字符串一样打印到控制台。当使用函数执行括号 ...newValue() 我得到这不是来自 node.js 的函数。
-
发布您的更新代码
标签: javascript json mongoose