Is there a way to execute a function from String passed as a request parameter and return result in node.js ? Imagine a request which contains String:
"db.users.find()"
as a parameter
If I knew I wanted to execute this statement I would do this:
db.collection('users', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
What I want is something like a parser which would execute given statement and returned results.
I tried like this:
exports.execStatement = function(req, res) {
//var statemnet = req.params.statement;
var statement = "collection.find().toArray(function(err, items) {
res.send(items);});";
db.collection('users', function(err, collection) {
eval(statement)
});
};
This code gives me error:
var statement = "collection.find().toArray(function(err, prdel) { ...
SyntaxError: Unexpected token ILLEGAL
What is wrong ? Why can't I execute code stored in a String ? After this works I would like to figure out how to execute code which is passed as a parameter in request.
Is this approach even possible ?
The second example shows how you can add a function to a db.
http://mongodb.github.com/node-mongodb-native/api-generated/db.html#eval
However DON'T. There are three main reasons