Reputation: 41
I am converting my database connection to MongoClient and am having difficulty changing parts of my previous code over.
Previously, in order to retrieve all documents from a collection, I would use:
$.getJSON('/users/infolist', function(data) {
$.each(data, function(){
//cycles through each document and do whatever
});
});
which would call the following:
router.get('/infolist', function(req, res) {
var db = req.db;
var collection = db.get('empcollection');
collection.find({$query: {}, $orderby: {age:1}},{},function(e,docs){
res.json(docs);
});
});
After looking at documentation online, I still have not figured out how to replicate this behavior with MongoClient. I have established connection, and can query the database, but returning the collection, and cycling through each document as done above is not working.
Any advice or help would be greatly appreciated.
Upvotes: 2
Views: 192
Reputation: 5908
From your explanation, I understand that you want to use the native mongodb
driver to retrieve a list of documents from your collection, update them using a loop, and then retrieving them to the client:
var MongoClient = require('mongodb').MongoClient;
//Establish a connection to your database
MongoClient.connect('mongodb://your/connection/string', function(err, db) {
if(err) {
console.log('There was an error connecting to the database');
}
//Map empcollection to a variable
var collection = db.collection('empcollection');
//Query the collection and retrieve the documents in an array
collection.find({}).toArray(function(err, docs)) {
if(err) {
console.log('There was an error retrieveing the matched documents');
}
//Loop through the documents and change them accordingly
for(var i = 0; i < docs.length; i++) {
//........
}
//Retrieve the updated data
res.json(docs);
}
});
});
Upvotes: 1