javascript - MongoDB 不限于查询字段

标签 javascript node.js mongodb

我有一个 mongodb 查询,其中请求有限数量的字段。但它仍然返回整行。有人可以帮忙吗?

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');
        }
    );

最佳答案

由于您使用的是 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 对此进行了测试,但我刚刚注意到您似乎使用的是普通的 http;不过,我认为它仍然可以工作)

关于javascript - MongoDB 不限于查询字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19229723/

相关文章:

php - 从 PHP 调用 Javascript 函数

javascript - 在检索到内容之前如何隐藏 jquery 对话框?

javascript - Heroku 找不到我的 index.js 文件

javascript - Node.js for 循环 : strange behavior

python - 如何在 Linux 上递归提取数据?

javascript - 免费的 jQuery Grid,支持卡住列和动态数据

javascript - HttpClient PostAsync 在 JQuery 中等效于 FormURLEncodedContent 而不是 JSON

node.js - 无法将文件读取流从 Google Cloud Storage 传输到 Google Drive API

python - 使用mongo-connector的部分单词搜索在Elasticsearch(elasticsearch-py)中不起作用

mysql - 同时使用 MongoDB 和 MySQL 的 Hadoop 配置