Javascript 将JSON字符串转换为对象
我在JavaScript Express.js/Mongoose中有这样一个JSON:Javascript 将JSON字符串转换为对象,javascript,json,mongoose,Javascript,Json,Mongoose,我在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)" } }); 现在我想使用这个字符串作为对象。这能实现吗 e、 g
// create a document
var demo = new DemoSchema({
hat: { money: "500" },
functions: {
func1: "this.hat.money - (0.02*this.hat.money)"
}
});
现在我想使用这个字符串作为对象。这能实现吗
e、 g
有关为什么要这样做的更多背景信息:
指针:
更新的代码:除了我们与Brennan合作开发的JavaScript唯一解决方案外,以下解决方案将适用于mongoose存储函数:
var mongoose = require('mongoose')
require('mongoose-function')(mongoose);
var mySchema = mongoose.Schema({ func: Function });
var M = mongoose.model('Functions', mySchema);
var m = new M;
m.func = function(){
console.log('stored function')
}
m.save(function (err) {
M.findById(m._id, function (err, doc) {
doc.func(); // logs "stored function"
});
});
另请参见:为什么函数是字符串而不是函数?我会让它:func1:function{this.hat.money-0.02*this.hat.money}有趣,但有两个问题:如何执行该函数,以及是否有可能在demo.functions.func1中更改这些函数?我不知道Express或Mongoose是如何工作的,所以我不能确切地告诉你,但调用它就像调用任何其他函数一样:console.log“%s”减少2%,demo.hat.newValue;您将无法编辑函数内部的内容,但您可以始终将func1重置为新函数。我明白了。我尝试过这个建议,但即使将其定义为函数,它也会像字符串一样打印到控制台。当使用函数execution parantheses…newValue时,我得到的不是node.js中的函数
var mongoose = require('mongoose')
require('mongoose-function')(mongoose);
var mySchema = mongoose.Schema({ func: Function });
var M = mongoose.model('Functions', mySchema);
var m = new M;
m.func = function(){
console.log('stored function')
}
m.save(function (err) {
M.findById(m._id, function (err, doc) {
doc.func(); // logs "stored function"
});
});