F4LLCON F4LLCON - 1 year ago 123
Node.js Question

node js db.get is not a function

I am having this error I can't figure out how to fix;

TypeError: db.get is not a function


module.exports = {
'url' : 'mongodb://localhost/database'


// server.js

// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

var db = require('./config/database.js');

// configuration ===============================================================
mongoose.connect(db.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({ secret: 'secretkeykeykeykey' })); // session secret
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================
require('./app/routes/routes')(app, passport); // load our routes and pass in our app and fully configured passport
var boxes = require('./app/routes/boxes');

// Make our db accessible to our router
req.db = db;

app.use('/portal', boxes);

// launch ======================================================================
console.log('The magic happens on port ' + port);


var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BoxlistSchema = new Schema({
name: {
type: String
//insert your other key of collection

module.exports = mongoose.model('Boxlist', BoxlistSchema);


var express = require('express');
var router = express.Router();
var collection = require('./boxlist');

* GET boxlist.
router.get('/boxlist', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');

* POST to addbox.
router.post('/addbox', function(req, res) {
var db = req.db;
// var collection = db.get('boxlist');
db.collection.insert(req.body, function(err, result){
(err === null) ? { msg: '' } : { msg: err }

* DELETE to deletebox.
router.delete('/deletebox/:id', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
var boxToDelete = req.params.id;
collection.remove({ '_id' : boxToDelete }, function(err) {
res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });

module.exports = router;


// Boxlist data array for filling in info box
var boxListData = [];

// DOM Ready =============================================================
$(document).ready(function () {

// Populate the box table on initial page load

// Boxname link click
$('#boxList table tbody').on('click', 'td a.linkshowbox', showBoxInfo);

// Add Box button click
$('#btnAddBox').on('click', addBox);

// Delete Box link click
$('#boxList table tbody').on('click', 'td a.linkdeletebox', deleteBox);


// Functions =============================================================

// Fill table with data
function populateTable() {

// Empty content string
var tableContent = '';

// jQuery AJAX call for JSON
$.getJSON('/portal/boxlist', function (data) {

// Stick our box data array into a boxlist variable in the global object
boxListData = data;

// For each item in our JSON, add a table row and cells to the content string
$.each(data, function () {
tableContent += '<tr>';
tableContent += '<td><a href="#" class="linkshowbox" rel="' + this.boxname + '" title="Show Details">' + this.boxname + '</a></td>';
tableContent += '<td>' + this.vm + '</td>';
tableContent += '<td><a href="#" class="linkdeletebox" rel="' + this._id + '">delete</a></td>';
tableContent += '</tr>';

// Inject the whole content string into our existing HTML table
$('#boxList table tbody').html(tableContent);

// Show Box Info
function showBoxInfo(event) {

// Prevent Link from Firing

// Retrieve boxname from link rel attribute
var thisBoxName = $(this).attr('rel');

// Get Index of object based on id value
var arrayPosition = boxListData.map(function (arrayItem) {
return arrayItem.boxname;

// Get our Box Object
var thisBoxObject = boxListData[arrayPosition];

//Populate Info Box


// Add Box
function addBox(event) {

// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addBox input').each(function (index, val) {
if ($(this).val() === '') {

// Check and make sure errorCount's still at zero
if (errorCount === 0) {

// If it is, compile all box info into one object
var newBox = {
'boxname': $('#addBox fieldset input#inputBoxName').val(),
'init': $('#addBox fieldset input#inputBoxInit').val(),
'vm': $('#addBox fieldset input#inputBoxVm').val(),
'description': $('#addBox fieldset input#inputBoxDescription').val(),
'version': $('#addBox fieldset input#inputBoxVersion').val()

// Use AJAX to post the object to our addbox service
type: 'POST',
data: newBox,
url: '/portal/addbox',
dataType: 'JSON'
}).done(function (response) {

// Check for successful (blank) response
if (response.msg === '') {

// Clear the form inputs
$('#addBox fieldset input').val('');

// Update the table

} else {

// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);

} else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;

// Delete Box
function deleteBox(event) {


// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this box?');

// Check and make sure the box confirmed
if (confirmation === true) {

// If they did, do our delete
type: 'DELETE',
url: '/portal/deletebox/' + $(this).attr('rel')
}).done(function (response) {

// Check for a successful (blank) response
if (response.msg === '') {} else {
alert('Error: ' + response.msg);

// Update the table


} else {

// If they said no to the confirm, do nothing
return false;




<!-- views/profile.ejs -->
<!doctype html>

<title>Vagrant CLI Node API</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
body {
padding-top: 80px;
word-wrap: break-word;
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/global.js"></script>

<div class="container">

<div class="page-header text-center">
<h1><span class="fa fa-th"></span> Portal</h1>
<a href="/profile" class="btn btn-default btn-sm">Profile</a>
<a href="/logout" class="btn btn-default btn-sm">Logout</a>

<div class="row">

<div class="col-sm-6">
<div id="boxList" class="well">
<h3><span class="fa fa-th"></span> Available Boxes</h3>

<table class="table">


<!-- BOX INFO -->
<div class="col-sm-6">
<div class="well" id="boxInfo">
<h3><span class="fa fa-th"></span> Box info</h3>

<strong>Select box name for more information</strong>

<p><strong>Name:</strong> <span id='boxInfoName'></span>
<br/><strong>Vm:</strong> <span id='boxInfoVm'></span>
<br/><strong>Description:</strong> <span id='boxInfoDescription'></span>
<br/><strong>Version:</strong> <span id='boxInfoVersion'></span></p>

<a class="fa fa-plus" href="#">
<i></i> start box instance and add to account</a>


<!-- ADD NEW BOX -->
<div class="col-sm-6">
<div class="well">
<h3><span class="fa fa-th"></span> Add box</h3>

<strong>Add new box to `available boxes`</strong>

<form id="addBox" class="form-inline" action="/portal/addbox" method="post">
<fieldset class="form-group">
<input id="inputBoxName" type="text" class="form-control" placeholder="Boxname" />
<input id="inputBoxInit" type="text" class="form-control" placeholder="Init" />
<input id="inputBoxVm" type="text" class="form-control" placeholder="Vm" />
<input id="inputBoxVersion" type="text" class="form-control" placeholder="Description" />
<input id="inputBoxDescription" type="text" class="form-control" placeholder="Version" />
<button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>





Does anybody know what's going on and how to fix this? My code excludes node_modules link to dropbox

PS. Parts of these codes are from this tutorial: link which can be forked from GitHub: link. This code works, but I've implemented it into my own application and as far as I know it's now the same code, but I get the error in my app, but not in his app.

Answer Source

Do one thing, remove db.get('boxlist');

Make a new file with the name boxlist

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BoxlistSchema = new Schema({
      name: {
           type: String
      //insert your other key of collection

module.exports = mongoose.model('Boxlist', BoxlistSchema);

In your boxes.js add

var collection = require('/boxlist');

now you can directly use queries,need not use var collection = db.get('boxlist');

Just delete this line from the code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download