Reputation: 1
I'm currently having trouble getting anything from my mongodb collection "media" with attributes "title" and "author" (among others, but these are just two for purpose of illustration). The following code prints "undefined to console".
var db = require('monk')(config['dbPath']);
var medialist = db.get('media');
var foundItems = medialist.find();
var firstFoundItem = JSON.stringify(foundItems[0]);
console.log(firstFoundItem);
Also, when the server is started, I get the following message in the console:
"{ [Error: Cannot find module '../build/Release/bson'] code'MODULE_NOT_FOUND'} js-bson: Failed to load c++ bson extension, using pure JS version"
After searching that error message on Google, I've tried a few solutions including installing npm bson. Is it just my code that isn't working, or is it the missing module (or both)?
Thanks,
musical
EDIT: Going by what @hassansin suggested about async calls, I tried the following, which now gives me "cannot read property 'then' of undefined at e:\Dev\BookWyrm\api\userRouter.js:16:43
var err;
var params = req.params;
mongoHandler.getMedia(err, params)
.then(function(itemList) {
if (!err) {
var firstFoundItem = JSON.stringify(itemList[0]);
console.log(firstFoundItem);
res.sendFile('medialist.html', {
root: './public/views/'
});
} else {
res.sendFile('errorpage.html', {
root: './public/views/'
});
}
});
});
And mongoHandler is the following module:
var config = require('../config.json');
//var db = require('monk')('localhost:27017/bookwyrm');
var mongo = require('mongodb');
var server = new mongo.Server('localhost', 27017, {
auto_reconnect: true
});
var db = new mongo.Db('bookwyrm', server);
function getMedia(err, params) {
var callback = {};
asyncGet(err, callback);
if (!err) {
return callback.items;
} else {
console.log("Connection or query to mongodb failed");
}
}
function asyncGet(err, callback) {
db.open(function(err, db) {
if (!err) {
db.collection('media', function(err, collection) {
if (!err) {
collection.find(params).toArray(function(err, items) {
if (!err) {
db.close();
callback.items = items;
} else {
errorHandler(err, callback);
}
})
} else {
errorHandler(err, callback);
}
})
} else {
errorHandler(err, callback);
}
});
}
function errorHandler(err, callback) {
if (!db) {
db.close()
};
callback.err = err;
}
module.exports.getMedia = getMedia;
Upvotes: 0
Views: 1515
Reputation: 17508
You have couple of problems with your script. First you didn't specify database name and second, find
is an asynchronous operation, reading the return value of async method won't give you the result.
var db = require('monk')('localhost:27017/dbname'); // <- database name
var medialist = db.get('media');
medialist.find({})
.then(function(foundItems){ // <- use promise or callback to get result
var firstFoundItem = JSON.stringify(foundItems[0]);
console.log(firstFoundItem);
})
Upvotes: 1