Dillip Kumar Pradhan
Dillip Kumar Pradhan

Reputation: 33

Querying result from mongoose using dynamic model.find

I need to find the results of a query with mongoose find({}) method in Node.js with a variable containing model name.

var adSchema     =  new Schema({ schema defination });
var Ad           =  mongoose.model('Ad', adSchema);
var variableName = 'Ad';
variableName.find({}).exec(function (err, adObj) {});

Is it possible or not?

Thanks in advance

Upvotes: 3

Views: 2061

Answers (2)

chirag
chirag

Reputation: 1779

Try this:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var anySchema = new Schema({
      fieldname:  String
    });
    var Test = mongoose.model('Test', anySchema);
    Test.find({}).exec(function(err,result){});

Upvotes: 0

DAXaholic
DAXaholic

Reputation: 35428

You should be able to do that when calling model with just the name like so

mongoose.model('Ad').find({}).exec(function (err, adObj) {});  

See here for the corresponding part of the official docs

Upvotes: 9

Related Questions