我遇到这个错误,无法解决。
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);
box.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, 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
$.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.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">
<style>
body {
padding-top: 80px;
word-wrap: break-word;
}
</style>
<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>
</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>
有人知道发生了什么事以及如何解决此问题吗?我的代码不包括node_modules link to dropbox
谢谢
PS。这些代码的一部分来自本教程:link,可以从GitHub:link分叉。该代码有效,但是我已经将其实现到自己的应用程序中,据我所知,现在它是相同的代码,但是我在应用程序中遇到错误,但在他的应用程序中却没有。
最佳答案
做一件事,删除db.get('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);
在您的box.js中添加
var collection = require('/boxlist');
现在您可以直接使用查询,不需要使用
var collection = db.get('boxlist');
只需从代码中删除此行。