mat*_*and 1 jquery mongoose mongodb node.js express
我刚刚进入Node,Express和Mongoose.到目前为止还爱它,但无法弄清楚如何将AJo调用中的MongoDB过滤传递给API.
我有一个简单的jQuery AJAX请求,如下所示:
$.getJSON('/api/products', {
filter: { status: 'active' } // <-- Want this to get processed by the API
}, function(products){
console.log(products);
});
Run Code Online (Sandbox Code Playgroud)
以下是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);
});
});
Run Code Online (Sandbox Code Playgroud)
您应该按照原样发送已编码的参数.现在您只需要获取它们并将其传递给您的查询:
// 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);
});
});
Run Code Online (Sandbox Code Playgroud)
那个循环就在那里,因为你可能想要检查发送的内容.但是我会把它留给你.
此外req.params,如果适合您的口味.