【问题标题】:Passing Node.js parameter into mongodb request将 Node.js 参数传递给 mongodb 请求
【发布时间】:2012-01-13 11:18:20
【问题描述】:

我正在使用 node.js 开发一个简单的 Web 服务。我正在使用 choreographer 来路由 http 调用。此代码工作正常:

router.get('/search/*', function(req, res, term){
  res.writeHead(200, {'Content Type:':'text/plain'});
  db.collection('foo').find({'a':1}).toArray(function(err, items){
  console.log(items);
    res.write(JSON.stringify(items));
    res.end();
   });
  });

如您所见,find 方法查找 {'a':1},这工作正常,返回一条记录。但是当我想将搜索词从路由器传递给查询时,我得到一个空响应:

router.get('/search/*', function(req, res, term){
  res.writeHead(200, {'Content Type:':'text/plain'});
  db.collection('foo').find({'a':term}).toArray(function(err, items){
  console.log(items);
    res.write(JSON.stringify(items));
    res.end();
   });
  });

有什么想法吗??

编辑:我已经检查了 term 的值,正如下面 cmets 中所建议的那样,它是 1,这是我所期望的。

【问题讨论】:

  • 你检查过 term 的值吗? console.log(term)
  • simplyharsh,是的,我有,正如预期的那样
  • 你检查过err的值吗?如果执行查询有任何问题,err 将是非空的,items 将是空的。经常检查是件好事。

标签: javascript node.js mongodb nosql


【解决方案1】:

会不会是 db-connection 比实际路由时间长?

如果您定义“术语”并获得响应,则很可能在 db 中找不到该术语,或者 db-connection 以某种方式失败。

一种方法是初始化并从回调函数调用 db。

router.get('/search/*', function(req, res, term){
  res.writeHead(200, {'Content Type:':'text/plain'});
  var db = new mongo.Db('dbname', server);
  db.open(function(err, db){
    db.createCollection("collection_name", function(err, collection){
      db.collection('foo').find({'a':term}).toArray(function(err, items){
        console.log(items);
      });
    });
  });
});

如果它有效,您可能需要添加一个 db.close();

保留语法错误。

【讨论】:

  • 'term'(1)肯定在数据库中,查询数据库时变量'term'已经正确初始化了
【解决方案2】:

我发现一种解决方法是构建一个新的 json 对象,然后将“a”参数设置为 term,例如

var searchterm = {'a':2};
searchterm.a = term;

我怀疑创建 JSON 对象有一些问题,我在这里没有完全理解。

【讨论】:

    猜你喜欢
    • 2016-04-01
    • 1970-01-01
    • 2015-08-27
    • 2018-02-27
    • 2019-09-29
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多