javascript - MongoDB not limiting to queried fields -


i have mongodb query in requesting limited number of fields. still returning entire row. can 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');         }     ); 

since you're using node-mongodb-native driver, should work (provided number of results isn't large, since toarray() reads results memory first before calling callback):

collection.find(   { username: searchterm },   { username: 1 } // [ 'username' ] works ).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'); }); 

if expect lot of results, want use streaming, perhaps using jsonstream:

// create cursor stream. var stream = coll.find(...).stream();  // set correct content-type. res.setheader('content-type', 'application/json');  // pipe cursor stream, convert json, , write client. stream.pipe(jsonstream.stringify()).pipe(res); 

(i tested express noticed seem using plain http; think it'll still work, though)


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -