如何将字符串转换为对象?

时间:2013-03-01 09:58:56

标签: javascript node.js mongodb dereference node-mongodb-native

我有这段代码:

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

});

它按预期工作得很好。现在我希望能够使用任意字段而不是“名称”,所以我测试了这个:

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

});

哪个不起作用。有什么问题以及用变量调用collection.find()的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

您必须使用方括号表示法在调用之外构建find参数对象:

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

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

答案 1 :(得分:1)

尝试此变体

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