我在mongodb中有几张名字相似的表:
var fruit_prices = db.collection('fruit_prices');
var vegetables_prices = db.collection('vegetables_prices');
var tuber_prices = db.collection('tuber_prices');
以下代码必须适用于这三个表。为此,我需要将food_type变量的值转换为之前定义的三个变量之一,以便稍后我可以在任何表中调用find方法:
// food_type can be fruit, vegetables or tuber
var table = food_type+'_prices';
// instead of [table] i should use another expression that works..this is not working
[table].find({},{'_id': false}).toArray(function(err, docs) {
//whatever here
});
如何做到这一点?
此致
答案 0 :(得分:1)
您可以将所有这三个放在一个物体上:
var prices = {
fruit: db.collection('fruit_prices'),
vegetables: db.collection('vegetables_prices'),
tuber: db.collection('tuber_prices')
};
然后当你需要使用一个时:
var food = 'fruit';
prices[food].find({},{'_id': false}).toArray(function(err, docs) {
//whatever here
});