HideAndSeek HideAndSeek - 2 years ago 152
Node.js Question

How to automatically create a REST API node.js / MongoDB

I am running a node.js Server that handles REST Api calls.
The response of those calls will be either one or a list of MongoDB objects (JSON).

I already read about parameters and how to handle them. But is there any way to automatically do this?

Lets say I have a User Collection:

name: String,
hobby: String,
age: Number

Now I want to get a list of all Users that are of Age=18.

I know that I can recover parameters like this:

url: http://localhost:3000/user?age=18&hobby=something

var app = express();
app.get('/user', function (req,res) {

var age=req.query.age;
var hobby=req.query.hobby;


But assume that the user has 10 different properties and I have 15 different Collections. Can't I just do this dynamically? So I dont have to recover every possible parameter?

I want to be able search the MongoDB the way that all given parameters are used.

I hope I could express myself good enough :D Thanks!

Answer Source

Because the req.query returns a JS object after the query string is parsed where the object will have properties defined in the query string, e.g:


req.query will return the object { name: "andrew", age: "22" }

and thus it can be used as the find() method argument as long as the properties in the object match the underlying collection document schema.

You can then do:

app.get('/user', function (req, res) {
    User.find(req.query, function (err, users){ ... });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download