0

I have such a JSON in JavaScript (Express.js/Mongoose):

// create a document
var demo = new DemoSchema({
    hat: { money: "500" },
    functions: {
                func1: "this.hat.money - (0.02*this.hat.money)"
               }
});

Now I want to use this string as objects. Can it be achieved?

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)

More Background Info about why to do it this way: https://groups.google.com/forum/#!topic/mongoose-users/lzyjg0b8Vn0

Pointers: String to object in JS

Updated Code: http://jsfiddle.net/nottinhill/uktLr2g5/

Community
  • 1
  • 1
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
  • 1
    Why is your function a string and not a function? I would make it: `func1: function() {this.hat.money - (0.02*this.hat.money) }` – Brennan Nov 06 '14 at 16:58
  • Interesting, two questions though: How to execute that function and will it be possible to alter such inside demo.functions.func1 ? – Stephan Kristyn Nov 06 '14 at 17:07
  • I don't know how Express or Mongoose work, so I can't tell you exactly, but you call it just like you would any other function: `console.log('%s is 2% less', demo.hat.newValue());` And you won't be able to edit what is inside the function, but you can always reset func1 to a new function. – Brennan Nov 06 '14 at 17:10
  • I see. I tried this suggestion, but even when defining this as function it gets printed to the console as if it were a string. When using the function execution parantheses ...newValue() I am getting this is not a function from node.js. – Stephan Kristyn Nov 06 '14 at 17:17
  • Post your updated code – Brennan Nov 06 '14 at 17:17
  • http://jsfiddle.net/nottinhill/uktLr2g5/ – Stephan Kristyn Nov 06 '14 at 17:27
  • This is how I would handle it: http://jsfiddle.net/uktLr2g5/4/ Like I said though, mongoose/express is not something I know about, so can't really provide much further assistance – Brennan Nov 06 '14 at 17:31
  • Latest Iteration works - http://jsfiddle.net/nottinhill/uktLr2g5/5/ I will report if I get it to run in Mongoose this way. How would you set "func1" to be a new function? – Stephan Kristyn Nov 06 '14 at 17:32

1 Answers1

0

In addition to the JavaScript-only solution we worked out with Brennan at http://jsfiddle.net/nottinhill/uktLr2g5/5 the following solution will work for mongoose for storing functions:

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"
  });
});

Also see: https://github.com/aheckmann/mongoose-function

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147