0

I have a mongodb query in which I am requesting for a limited number of fields. But it is still returning the entire row. Can someone help?

collection.find(
        { username: searchterm },
        { username: 1 }, 
        function(e, docs){
            console.log('---- DB RESULT');
            console.log(docs);
            res.writeHead(200, {'content-type': 'text/json' });
            res.write( JSON.stringify({ 'docs' : docs }) );
            res.end('\n');
        }
    );
4

1 回答 1

3

由于您正在使用node-mongodb-native驱动程序,这应该可以工作(前提是结果的数量不是太大,因为toArray()在调用回调之前首先将所有结果读入内存):

collection.find(
  { username: searchterm },
  { username: 1 } // [ 'username' ] works too
).toArray(function(e, docs) {
  // TODO: handle error...
  console.log('---- DB RESULT');
  console.log(docs);
  res.writeHead(200, {'content-type': 'text/json' });
  res.write( JSON.stringify({ 'docs' : docs }) );
  res.end('\n');
});

如果您期望很多结果,您可能想要使用流式传输,也许使用JSONStream

// Create a cursor stream.
var stream = coll.find(...).stream();

// Set correct Content-Type.
res.setHeader('Content-Type', 'application/json');

// Pipe cursor stream, convert it to JSON, and write to the client.
stream.pipe(JSONStream.stringify()).pipe(res);

(我用Express对此进行了测试,但我只是注意到您似乎在使用 plain http;不过我认为它仍然可以工作)

于 2013-10-07T17:18:24.243 回答