将GETparameter passing给Express + Mongoose Restful API

我刚刚进入Node,Express和Mongoose。 到目前为止,爱不释手,但无法弄清楚如何将来自AJAX调用的MongoDB过滤传递给API。

我有一个简单的jQuery AJAX请求是这样的:

$.getJSON('/api/products', { filter: { status: 'active' } // <-- Want this to get processed by the API }, function(products){ console.log(products); }); 

这里是我的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); }); }); 

你应该发送编码的参数与你的要求,因为它是。 现在你只需要把它们传递给你的查询:

 // 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); }); }); 

那个循环在那里,因为你可能想检查发送的内容。但是我会把它留给你。

如果这符合你的口味也req.params