admin管理员组

文章数量:1026399

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

TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5

database.js

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

server.js

// 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.initialize());
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
app.use(function(req,res,next){
    req.db = db;
    next();
});

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

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

boxlist.js

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);

boxes.js

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');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

/*
 * 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){
        res.send(
            (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;

global.js

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

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

    // Populate the box table on initial page load
    populateTable();

    // 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
    event.preventDefault();

    // 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;
    }).indexOf(thisBoxName);

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

    //Populate Info Box
    $('#boxInfoName').text(thisBoxObject.fullname);
    $('#boxInfoVm').text(thisBoxObject.vm);
    $('#boxInfoDescription').text(thisBoxObject.description);
    $('#boxInfoVersion').text(thisBoxObject.version);

};

// Add Box
function addBox(event) {
    event.preventDefault();

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

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

        // If it is, pile 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
        $.ajax({
            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
                populateTable();

            } 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) {

    event.preventDefault();

    // 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
        $.ajax({
            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
            populateTable();

        });

    } else {

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

    }

};

portal.js

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

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

<body>
    <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>

        <div class="row">

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

                    <table class="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Vm</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>

                </div>
            </div>

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

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

                    <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>

                </div>
            </div>

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

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

                    <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" />
                            <br>
                            <br>
                            <button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
                        </fieldset>
                    </form>

                </div>
            </div>

        </div>

    </div>
</body>

</html>

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

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.

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

TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5

database.js

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

server.js

// 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.initialize());
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
app.use(function(req,res,next){
    req.db = db;
    next();
});

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

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

boxlist.js

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);

boxes.js

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');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

/*
 * 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){
        res.send(
            (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;

global.js

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

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

    // Populate the box table on initial page load
    populateTable();

    // 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
    event.preventDefault();

    // 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;
    }).indexOf(thisBoxName);

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

    //Populate Info Box
    $('#boxInfoName').text(thisBoxObject.fullname);
    $('#boxInfoVm').text(thisBoxObject.vm);
    $('#boxInfoDescription').text(thisBoxObject.description);
    $('#boxInfoVersion').text(thisBoxObject.version);

};

// Add Box
function addBox(event) {
    event.preventDefault();

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

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

        // If it is, pile 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
        $.ajax({
            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
                populateTable();

            } 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) {

    event.preventDefault();

    // 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
        $.ajax({
            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
            populateTable();

        });

    } else {

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

    }

};

portal.js

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

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

<body>
    <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>

        <div class="row">

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

                    <table class="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Vm</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>

                </div>
            </div>

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

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

                    <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>

                </div>
            </div>

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

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

                    <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" />
                            <br>
                            <br>
                            <button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
                        </fieldset>
                    </form>

                </div>
            </div>

        </div>

    </div>
</body>

</html>

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

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.

Share Improve this question edited Jul 21, 2016 at 20:47 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Jul 21, 2016 at 11:38 MOTIVECODEXMOTIVECODEX 2,75214 gold badges46 silver badges78 bronze badges 7
  • It look like you don't have any get method in yout database.js module. Not sure you're omitting the code, but for sure you have to provide the full code if you have. Or follow a tutorial, if this is all your real code. Than e back here if you still have issues. – Mario Santini Commented Jul 21, 2016 at 11:44
  • unable to understand `var collection = db.get('boxlist'); ,is it the plete code? – Ajitej Kaushik Commented Jul 21, 2016 at 11:47
  • Added the entire code in server, database and boxes js. I've added passport to my app and that works, I can create the passport user database and add users to it. But I am also trying to create new boxes which I get this db.get error. – MOTIVECODEX Commented Jul 21, 2016 at 11:51
  • Is the database.js file content mentioned in your question the one that is required using require('./config/database.js');? – Vincent Schöttke Commented Jul 21, 2016 at 11:57
  • It's under database.js. The code entirely works for passport auth., but not for the other part. – MOTIVECODEX Commented Jul 21, 2016 at 12:00
 |  Show 2 more ments

2 Answers 2

Reset to default 2

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.

You have to define port number for accessing database.

Eg:

mongodb://localhost:27017/database

To fetch collection follow documentation https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

var collection = db.collection('test');

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

TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5

database.js

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

server.js

// 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.initialize());
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
app.use(function(req,res,next){
    req.db = db;
    next();
});

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

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

boxlist.js

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);

boxes.js

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');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

/*
 * 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){
        res.send(
            (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;

global.js

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

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

    // Populate the box table on initial page load
    populateTable();

    // 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
    event.preventDefault();

    // 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;
    }).indexOf(thisBoxName);

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

    //Populate Info Box
    $('#boxInfoName').text(thisBoxObject.fullname);
    $('#boxInfoVm').text(thisBoxObject.vm);
    $('#boxInfoDescription').text(thisBoxObject.description);
    $('#boxInfoVersion').text(thisBoxObject.version);

};

// Add Box
function addBox(event) {
    event.preventDefault();

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

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

        // If it is, pile 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
        $.ajax({
            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
                populateTable();

            } 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) {

    event.preventDefault();

    // 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
        $.ajax({
            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
            populateTable();

        });

    } else {

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

    }

};

portal.js

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

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

<body>
    <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>

        <div class="row">

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

                    <table class="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Vm</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>

                </div>
            </div>

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

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

                    <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>

                </div>
            </div>

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

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

                    <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" />
                            <br>
                            <br>
                            <button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
                        </fieldset>
                    </form>

                </div>
            </div>

        </div>

    </div>
</body>

</html>

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

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.

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

TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5

database.js

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

server.js

// 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.initialize());
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
app.use(function(req,res,next){
    req.db = db;
    next();
});

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

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

boxlist.js

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);

boxes.js

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');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

/*
 * 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){
        res.send(
            (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;

global.js

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

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

    // Populate the box table on initial page load
    populateTable();

    // 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
    event.preventDefault();

    // 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;
    }).indexOf(thisBoxName);

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

    //Populate Info Box
    $('#boxInfoName').text(thisBoxObject.fullname);
    $('#boxInfoVm').text(thisBoxObject.vm);
    $('#boxInfoDescription').text(thisBoxObject.description);
    $('#boxInfoVersion').text(thisBoxObject.version);

};

// Add Box
function addBox(event) {
    event.preventDefault();

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

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

        // If it is, pile 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
        $.ajax({
            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
                populateTable();

            } 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) {

    event.preventDefault();

    // 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
        $.ajax({
            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
            populateTable();

        });

    } else {

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

    }

};

portal.js

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

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

<body>
    <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>

        <div class="row">

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

                    <table class="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Vm</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>

                </div>
            </div>

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

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

                    <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>

                </div>
            </div>

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

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

                    <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" />
                            <br>
                            <br>
                            <button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
                        </fieldset>
                    </form>

                </div>
            </div>

        </div>

    </div>
</body>

</html>

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

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.

Share Improve this question edited Jul 21, 2016 at 20:47 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Jul 21, 2016 at 11:38 MOTIVECODEXMOTIVECODEX 2,75214 gold badges46 silver badges78 bronze badges 7
  • It look like you don't have any get method in yout database.js module. Not sure you're omitting the code, but for sure you have to provide the full code if you have. Or follow a tutorial, if this is all your real code. Than e back here if you still have issues. – Mario Santini Commented Jul 21, 2016 at 11:44
  • unable to understand `var collection = db.get('boxlist'); ,is it the plete code? – Ajitej Kaushik Commented Jul 21, 2016 at 11:47
  • Added the entire code in server, database and boxes js. I've added passport to my app and that works, I can create the passport user database and add users to it. But I am also trying to create new boxes which I get this db.get error. – MOTIVECODEX Commented Jul 21, 2016 at 11:51
  • Is the database.js file content mentioned in your question the one that is required using require('./config/database.js');? – Vincent Schöttke Commented Jul 21, 2016 at 11:57
  • It's under database.js. The code entirely works for passport auth., but not for the other part. – MOTIVECODEX Commented Jul 21, 2016 at 12:00
 |  Show 2 more ments

2 Answers 2

Reset to default 2

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.

You have to define port number for accessing database.

Eg:

mongodb://localhost:27017/database

To fetch collection follow documentation https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

var collection = db.collection('test');

本文标签: javascriptnode js dbget is not a functionStack Overflow