我有一个 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/