Reputation: 912
I'm just getting into Node, Express, and Mongoose. Loving it so far, but can't figure out how to pass MongoDB filtering from the AJAX call to the API.
I have a simple jQuery AJAX request like this:
$.getJSON('/api/products', {
filter: { status: 'active' } // <-- Want this to get processed by the API
}, function(products){
console.log(products);
});
Here are the important parts of my Express + Mongoose API:
// Define Mongoose Schema
var Schema = mongoose.Schema;
// Product Schema
var ProductSchema = new Schema({
name: { type: 'string', required: false },
price: { type: 'number', required: false },
status: { type: 'string', required: false },
description: { type: 'string', required: false },
});
// Product Model
var ProductModel = mongoose.model('Product', ProductSchema);
// Product Endpoint
app.get('/api/products', function(req, res){
return ProductModel.find(function(error, products){
return res.send(products);
});
});
Upvotes: 1
Views: 4739
Reputation: 151072
You should be sending the encoded paramters with your request as it is. Now you just need to get them and pass it to your query:
// Product Endpoint
app.get('/api/products', function(req, res){
var filter = {};
for ( var k in req.query.filter ) {
filter[k] = req.query.filter[k]; // probably want to check in the loop
}
return ProductModel.find(filter, function(error, products){
return res.send(products);
});
});
That loop is there because you might want to check what was sent in. But I'll leave that up to you.
Also req.params
if that suits your taste.
Upvotes: 6