Node.js MongoDB Express Mongoose应用程序抛出错误

Node.js MongoDB Express Mongoose App throwing errors

本文关键字:出错 错误 应用程序 Mongoose js MongoDB Express Node      更新时间:2023-09-26

这个问题有很多子问题,所以请耐心等待。我已经超过了截止日期,我至少需要在这个应用程序上取得一些进展。我正试图将YouTube视频的链接(带日期)存储在MongoDB数据库中,然后每天(根据日期)访问它们,并将它们放在旋转木马中。

该应用程序有两个视图:视频转盘,其中将显示YouTube视频(这应该会向数据库发出GET请求);以及数据库视图,其中:具有输入带有日期的新视频链接的表单;显示了由YouTube链接和日期组成的数据存储;并且如果必须输入特定日期的新视频,则允许用户删除条目。

因此,我当前的代码是:因此,运行该应用程序的server.js文件是:

//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');
//create an express app
var app = express();
var routes = require('./routes/index');
var database = require('./routes/database');
//view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
//set up the connection to the static files
    app.use('/public', express.static(__dirname + '/public'));
    app.use(express.static(__dirname + '/public'));

    app.use(bodyParser.json());
    //make the db accessible to the router
    app.use(function(req, res, next) {
        //req.db = db;
        next();
    });
    //set up the routing
    app.use('/', routes);
    app.use('/database', database);
//start the server on the port 8080
app.listen(8080);
//Send a message to the console
console.log('The server has started');

然后,数据库路由(database.js)的代码如下:

//Set up Express
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var app = express();
//connect to the data store and the set up the database
var db = mongoose.connection;
//connect to the database
mongoose.connect('mongodb://localhost/Mandela_Diaries');
//Create a model which connects to the schema and entries collection in the Mandela_Diaries database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
    console.log("mongodb is connected!");
});

//The route for getting data for the database - GET form
router.get("/database", function(req, res) {
    //Send the current entries to the page
    Entry.find({}, function(err, entries) {
        console.log(entries);
        if(err) {
            res.status(404).json({"error": "not found", "err":err});
            return;
        }
        //res.json(data);
        res.render(
            './views/database.html', {"root": __dirname + ''}
            );
    });
});
//The route for posting data on the database - POST form
router.post("/database", function(req, res) {
    //test new post
    console.log(req.body);
    var newEntry = new Entry({entry: {'date': req.body.date, 'link': req.body.string}});
        newEntry.save(function(err, result) {
            if (err !== null) {
                //object was not save
                res.status(500).json({error: "save failed", err: err});
                    } else {
                res.status(201).json(result);
        };
    });
});

索引路径(也就是视频链接将进入转盘的主页)(GET)的代码如下:

//Set up Express
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var app = express();
/*connect to the data store on the set up the database
var db = mongoose.connection;
mongoose.connection.on("open", function() {
    console.log("mongodb is connected!");
});*/
//create an express route for the home page at http://localhost:8080/
router.get('/', function(req, res) {
    res.render('./views/index.html', {"root": __dirname + ''});
});
module.exports = router;

最后是数据库的html文件.html,其中数据库被更新并显示如下:

<!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>The Mandela Diaries</title>
            <!-- For IE8 compatability mode -->
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <!-- To ensure that the website consumes all the space available inside the browser window -->
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- The CSS files including Bootstrap and custom CSS -->
            <!-- The CSS Bootstrap CSS file -->
            <!-- <link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.css"> -->
            <link rel="stylesheet" type="text/css" href="../public/css/bootstrap.css">
            <link rel="stylesheet" type="text/css" href="../public/css/bootstrap-theme.css">
            <!-- The custom CSS files 
            <link rel="stylesheet" type="text/css" href="style.css"> -->
            <!-- External scripts -->
            <script type="text/javascript" src="public/js/script.js"></script>

        </head>
        <body>
            <div class="container">
                <div class="row">
                    <div class="col-s-12">
                        <h1>The Mandela Diaries Database</h1>
                    </div>
                </div>
                <div class="row">
                    <div class="col-s-4">
                        <h3>Add Entry</h3>
                    </div>
                </div>
                <div class="row">
                    <div class="col-s-12">
                        <form class="form-inline">
                            <div class="form-group">
                                <label for="date">Date: </label>
                                <input type="date" class="form-control" id="date">
                            </div>
                            <div class="form-group">
                                <label for="link">Link: </label>
                                <input type="string" class="form-control" id="link">
                            </div>
                            <button type="submit" class="btn btn-default">Submit</button>
                        </form>
                    </div>
                </div>
                <div class="row">
                    <div class="col-s-12" id="entries">
                        <ul></ul>
                    </div>
                </div>
            </div>
            <script type="text/javascript" src="../public/js/jquery.js"></script>
            <script type="text/javascript" src="../public/js/bootstrap.js"></script>
        </body>
    </html>

显示转盘的主页的html文件如下:

<!DOCTYPE HTML>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>The Mandela Diaries</title>
            <!-- For IE8 compatability mode -->
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <!-- To ensure that the website consumes all the space available inside the browser window -->
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- The CSS files including Bootstrap and custom CSS -->
            <!-- The CSS Bootstrap CSS file -->
            <!-- <link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.css"> -->
            <link rel="stylesheet" type="text/css" href="../public/css/bootstrap.css">
            <link rel="stylesheet" type="text/css" href="../public/css/bootstrap-theme.css">
            <!-- The custom CSS files 
            <link rel="stylesheet" type="text/css" href="style.css"> -->

        </head>
        <body id="container">
            <div class="span8">
    <div id="myCarousel" class="carousel slide">
        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class=""></li>
            <li data-target="#myCarousel" data-slide-to="1" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="2" class=""></li>
        </ol>
        <div class="carousel-inner">
            <div class="item active">
                <iframe width="100%" height="100%" src="yesterday"></iframe>
            </div>
            <div class="item">
                <iframe width="100%" height="100%" src="today"></iframe>
            </div>
            <div class="item">
                <iframe width="100%" height="100%" src="tomorrow"></iframe>
            </div>
        </div>
        <a class="left carousel-control" href="#myCarousel" data-slide="prev">‹</a>
        <a class="right carousel-control" href="#myCarousel" data-slide="next">›</a>
    </div>
    </div>
            <script type="text/javascript" src="../public/js/jquery.js"></script>
            <script type="text/javascript" src="../public/js/bootstrap.js"></script>
        </body>
    </html>

即使代码在运行,我也会遇到一堆错误。首先,当我尝试访问索引("/")时,我会得到错误:Error: Cannot find module 'html'。当我尝试访问('/database')时,我会得到错误:"无法获取/databaseI don't know where我错在哪里了?"?我试图从很多教程中推断,尤其是这一个,但在这个阶段我完全迷失了方向。

发生Cannot GET /database是因为您创建的路由指向/database/database/,因为您执行app.use('/database', database);,然后在routes/database中执行router.get("/database", ...。您可以通过将routes/database.js文件更改为/而不是/database来解决此问题。

不确定我是否说清楚了。

您遇到的另一个问题是,您使用jade作为视图引擎,但您的视图是html。因此,您需要将视图更改为jade或将视图引擎更改为html。此外,视图的路径是错误的,因为您在routes文件夹中,并且希望转到views文件夹。

相关文章: