Search code examples
javascriptnode.jsmongodbdereferencenode-mongodb-native

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 ?


Solution

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