如何将string转换为对象?
我有这段代码:
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); }); });
它如预期般运作良好。 现在我想能够使用任意字段而不是“名称”,所以我testing了这个:
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()variables的正确方法是什么?
您将不得不使用方括号表示法在调用之外构buildfind
参数对象:
var toFind = {}; toFind[field] = regex; db.collection('coders', function(err, collection) { collection.find(toFind).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) { var findExpression = {}; findExpression[field]=regex; collection.find(findExpression).toArray(function(err, items) { res.send(items); }); });