2

I am trying to use node.js to provide json results from MongoDB.

var http = require('http');
var mongo = require('mongoskin');

http.createServer(function (req, res) {
  var args = req.url.split("/");
  console.log(args);
  var searchCollection = args[1];
  var searchVar = args[2];
  var searchString = args[3];
  var conn = mongo.db('user:pass@alex.mongohq.com:10039/name',{safe:true});
  conn.collection(searchCollection).find({searchVar:searchString}).toArray(function(err, items){
    if(err) throw err;
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(items));
  });
}).listen(process.env.PORT, process.env.IP);

The problem I am having is when I call the find function on the database it:-

  • searches for a document with a variable 'searchVar'
  • rather than searching for a variable with the value of the searchVar

Any help would be appreciated. Thanks!

4

1 回答 1

1

You will need to create your query object something like this:

var query = {};
query[searchVar] = searchString;

And then pass this into your query:

  conn.collection(searchCollection).find(query).toArray(function(err, items){
    if(err) throw err;
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(items));
  });
于 2012-11-22T16:04:25.367 回答