1

I'm using mongoose to query for one document, and I'd like to pipe it to a stream. My database has multiple account documents. If I simply:

db.Accounts.findOne({}).exec(function(err, data){
   ...
});

it correctly returns a single document. However,

var mongooseStream = db.Accounts.findOne({}).stream({ 
  transform: JSON.stringify
}),
  writeStream = require('fs').createWriteStream('accounts');

mongooseStream.pipe(writeStream);

this newly created writeStream above has every account listed inside of it.

Lastly, if I .find({}).limit(1).stream(), it will return only one document in the stream.

Any ideas on why streaming findOne({}) isn't working as I expect it to? Thanks!

mayorbyrne
  • 495
  • 1
  • 5
  • 16

1 Answers1

0

You have not put any condition on the findOne() and moreover you are streaming it. Therefore it is continuously doing findOne() and then supplying it to the stream. findOne() is used as follows :

SchemaModel.findOne({
     //conditions
},function(){
     //this is callback
});

From what i understand you are trying to do is, you are trying to stream only one document of the collection. For that i say, findOne is not what you need, because findOne is used to extract exactly one document directly in the form of Javascript object from the database when you define a set of condtions.

Read :

Mongoose Queries

db.Collection.findOne()

How to use mongoose findOne

Community
  • 1
  • 1
MegaMind
  • 653
  • 6
  • 31
  • Even with empty conditions in your code above, it will return one document using the callback method. I understand it's not the best method of writing one document to a stream, but I still am confused as to why it's returning more than one document/running findOne continuously (even when conditions are specified) – mayorbyrne Jun 09 '15 at 17:25
  • True it returns one document.. but mind that you are streaming the data here. – MegaMind Jun 10 '15 at 11:36