当查询过滤器在req.params.name中获取空值时,MongoDB findOne()不起作用

时间:2019-03-21 07:59:52

标签: node.js mongodb

我想创建一个GET api(使用mongodb,nodejs,router)以支持使用字段 name (字符串以及 null 值)上的过滤器来获取文档

当我使用http://localhost:3000/api/user/Sunil调用它时,输出:

{"_id":"5c90579f2473c915d277d3f6","name":"Sunil","age":36}

当我使用http://localhost:3000/api/user/null进行调用时,它不起作用:

null

req.params.name打印时为空

Console.log(req.params.name); // null

当我将查询过滤器硬编码为{name:null}时,得到的输出为:

{"_id":"5c925c396f98d910c0a09099","name":null,"age":null}

如何同时支持字符串查询和null查询?

代码:

api.get('/user/:name', function(req, res){
    // console.log(req.params.name);
    // const name = req.params.name;
    // console.log(name);
    db.collection("user").findOne({name: req.params.name}, function(err, data){
        if(err) throw err;
        // console.log(result);
        res.writeHead(200, {'Content-Type': 'application/json'});


        console.log(data);
        // result = {a: 1};

        res.end(JSON.stringify(result));

    });
});

0 个答案:

没有答案