将JSON字符串转换为对象

时间:2014-11-06 16:50:14

标签: 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。

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

指针: String to object in JS

更新代码http://jsfiddle.net/nottinhill/uktLr2g5/

1 个答案:

答案 0 :(得分:0)

除了我们在http://jsfiddle.net/nottinhill/uktLr2g5/5与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"
  });
});

另见:https://github.com/aheckmann/mongoose-function