I'm trying to learn more aboute node.js(express framework) and mongodb (official driver).
I've this code
db.open(function(err,db){
if(!err){
console.log ('we are connected');
db.collection('post',function(err,collection){
collection.find(function(err,posts){
if(!err){
res.json(posts);
}
});
});
}
});
It should query the db and print the results. But I cannot figure out how to print the query to the browser in json format.
I've already tried the JSON.stringify but without any result :(
Doing:
collection.find().toArray(function(err,posts){
if(!err){
res.json(posts);
}
});
(note the toArray function) it works, but I've heard that this is a bad practice because wastes a lot of memory.
Is there any more efficient way of doing it?
You can also use the cursor methods .each()
or .nextObject()
to operate on a single document at a time, without pulling everything into an array in memory like toArray()
does.
Details here: https://github.com/mongodb/node-mongodb-native/#find