2016-07-21 7 views
0

Ich habe diesen Fehler Ich kann nicht herausfinden, wie zu beheben;Knoten js db.get ist keine Funktion

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

Weiß jemand, was und wie geht dies zu beheben ? Mein Code schließt node_modules auslink to dropbox Danke

PS. Teile dieser Codes stammen aus diesem Tutorial: link, das von GitHub gespalten werden kann: link. Dieser Code funktioniert, aber ich habe ihn in meine eigene Anwendung implementiert, und soweit ich weiß, ist es jetzt derselbe Code, aber ich erhalte den Fehler in meiner App, aber nicht in seiner App.

+0

Es sieht so aus, als ob Sie keine 'get'-Methode in Ihrem' database.js' Modul haben. Ich bin mir nicht sicher, ob Sie den Code auslassen, aber Sie müssen natürlich den vollständigen Code angeben. Oder folge einem [tutorial] (http://blog.modulus.io/mongodb-tutorial), wenn das alles dein echter Code ist. Dann komm zurück, wenn du noch Probleme hast. –

+0

kann nicht verstehen 'var collection = db.get ('boxlist'); Ist es der vollständige Code? –

+0

Der gesamte Code in Server, Datenbank und Boxen js hinzugefügt. Ich habe einen Pass zu meiner App hinzugefügt, und das funktioniert. Ich kann die Benutzerdatenbank für den Pass erstellen und Benutzer hinzufügen. Aber ich versuche auch, neue Boxen zu erstellen, die ich diesen db.get Fehler bekomme. – MOTIVECODEX

Antwort

1

eine Sache tun, entfernen db.get('boxlist');

Machen Sie eine neue Datei mit dem Namen 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 Ihrem boxes.js hinzufügen

var collection = require('/boxlist');

jetzt direkt Abfragen verwenden können, nicht var collection = db.get('boxlist');

einfach löschen Sie diese Zeile aus dem Code verwenden müssen.

+0

Ich bekomme keine Boxliste gefunden ...... Muss ich boxlist.js in demselben Ordner wie boxes.js erstellen? Dann sollte der Pfad "require ('./ boxlist') sein;" Ich habe auch versucht "require ('./ app/routes/boxlist');" – MOTIVECODEX

+0

Da Sie den Pfad nicht richtig definieren, überprüfen Sie, wo Sie diese Datei abgelegt haben, wenn sie sich im selben Ordner wie boxes.js befindet. 'Var collection = require ('./ boxlist');' –

+0

Entschuldigung, mein Kopf ist Alle verwechselt. Ich erhalte den Fehler var Schema = require mongoose.Schema unerwarteter Bezeichner. boxlist.js: 2. Removed require und es startet. – MOTIVECODEX

1

Sie müssen die Portnummer für den Zugriff auf die Datenbank definieren.

ZB:

mongodb://localhost:27017/database 

Zur Sammlung Folge Dokumentation holen https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

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

Beide funktionieren, mit und ohne Port. Fehler immer noch da. – MOTIVECODEX

+0

"db.collection ist keine Funktion" Warum ist db.get anders? – MOTIVECODEX

+0

Ich habe versucht: 'mongoose.connect (db.url), Funktion (Fehler, db) { if (err) { Rückkehr console.dir (err); } db.get ('Boxliste', Funktion (Fehler, Sammlung) {}); }; 'in server.js, aber immer noch db.get keine Funktion in boxes.js – MOTIVECODEX