slezadav
slezadav

Reputation: 6141

How to cast string to object?

I have this piece of code :

var regex={"$regex":req.query.query,"$options":req.query.options }  

db.collection('coders', function(err, collection) {
    collection.find(

    {"name":regex}

    ).toArray(function(err, items) {
    res.send(items);
    });

});

it works pretty well as expected. Now I want to be able to use arbitrary field instead of "name", so I tested this:

    var regex={"$regex":req.query.query,"$options":req.query.options }

    var field="\"notName\""

db.collection('coders', function(err, collection) {
    collection.find(

    {field:regex}

    ).toArray(function(err, items) {
    res.send(items);
    });

});

which does not work. What is the problem and what is correct way of invoking collection.find() with variables ?

Upvotes: 1

Views: 140

Answers (2)

Silver_Clash
Silver_Clash

Reputation: 405

Try this variant

var regex={"$regex":req.query.query,"$options":req.query.options }
var field="notName";
db.collection('coders', function(err, collection) {
        var findExpression = {};
        findExpression[field]=regex;
        collection.find(findExpression).toArray(function(err, items) {
        res.send(items);
        });
});

Upvotes: 1

James Allardice
James Allardice

Reputation: 166031

You would have to build the find argument object outside of the call using square bracket notation:

var toFind = {};
toFind[field] = regex;

db.collection('coders', function(err, collection) {
    collection.find(toFind).toArray(function(err, items) {
        res.send(items);
    });
});

Upvotes: 1

Related Questions