1

I want to pass collection name in req.body and query the collection with that name .I tried this but its not working in mongoose

router.get('/data',(req,res)=>{
var mySchema="User"; // i will get it from req.body.model
    mySchema.find({},(err,docs)=>{
        if(err) throw err;
        res.json({
            success:true,
            data:docs
        });
    }); 
});
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
Gaurav Umrani
  • 124
  • 4
  • 12

3 Answers3

0

I really not encourage this practice but you can use eval()

var mySchema = "User";
eval(mySchema).find({},(err, docs) => {...

You can have a look at this question for more precision

Community
  • 1
  • 1
TGrif
  • 5,725
  • 9
  • 31
  • 52
  • Thanks its working, actually what i want is that in this route i am sending a keyword, and i want to check that keyword in all collections and based on that response is sent.. so not to query all collections, i am also sending collection name from req.body ....please provide another soultion of my problem – Gaurav Umrani Apr 19 '17 at 12:25
  • I'm not sure what you are trying to do but it seems that you should rethink your application structure. For a multi collection search, maybe _$lookup_ aggregation could help. – TGrif Apr 19 '17 at 12:57
  • @GauravUmrani I need to set the collection name dynamic for executing queries... I tried the above provided solution... but it showed me below error **TypeError: eval is not a constructor** Can we get other solution or get this above code working? – HARDIK THAKOR Apr 25 '17 at 03:25
0

I tried the above provided solution, as shown in the snippet below

let colName = 'users';
const dbModelObj = new eval(colName)(dataSet);

however it displayed error as below

TypeError: eval is not a constructor

HARDIK THAKOR
  • 161
  • 2
  • 12
0

I don't know why users above suggested use only eval. There is another way, by creating model dynamically.

let dynamicModels = {};
const schema = new Schema({}, {versionKey : false, strict: false});

const dynamicModel = (collection) => {
    if( !(collection in dynamicModels) ){
        dynamicModels[name] = connection.model(collection, schema, collection);
    }
    return dynamicModels[collectionName];
};

then you can use

const user = dynamicModel("user").findOne({})
Manvel
  • 750
  • 7
  • 10