DCr*_*z22 5 mongodb node.js monk
我的应用程序中有一部分可以指定一些过滤器来检索某些数据。但并非所有过滤器都是必需的,因此我可以将其中一些过滤器留空,并且查询不会使用它们。我怎样才能在 mongoDB 中实现这一点。提前致谢。
客户端:
$('#filter').click(function(e){
e.preventDefault();
var filters = JSON.stringify({ Marca : $('#Marca').val(), Modelo : $('#Modelo').val(), Fecha : $('#Fecha').val()});
$.ajax({
type: 'POST',
data: filters,
url: '/filterFees',
contentType: 'application/json'
}).done(function( response ) {
if(response.msg === ''){
filterFees(response.data);
}
else {
alert('Error: ' + response.msg);
}
})
})
Run Code Online (Sandbox Code Playgroud)
node.js(使用僧侣):
app.post('/filterFees', function(req, res){
var db = req.db;
var collection = db.get('Fees');
collection.find({'Marca' : req.body.Marca, 'Modelo' : req.body.Modelo, 'Fecha' : req.body.Fecha, },{},function(err,docs){
res.send((err === null) ? { msg: '', data : docs } : { msg:'error: ' + err });
});
})
Run Code Online (Sandbox Code Playgroud)
检查过滤器中是否存在该值
var filter = {}, filters;
if $('#Marca').val()
filter.Marca = $('#Marca').val();
if $('#Modelo').val()
filter.Modelo = $('#Modelo').val();
if $('#Fecha').val()
filter.Fecha = $('#Fecha').val()
filters = JSON.stringify(filter);
Run Code Online (Sandbox Code Playgroud)
并查找过滤器中的数据
collection.find(req.body,{},function(err,docs){
res.send((err === null) ? { msg: '', data : docs } : { msg:'error: ' + err });
});
Run Code Online (Sandbox Code Playgroud)
附言。不确定为什么要对参数进行字符串化而不是发送对象
| 归档时间: |
|
| 查看次数: |
2313 次 |
| 最近记录: |