无法 post 数据到数据库并且数据库未在 Robo 3T 中显示 (MongoDB/Mongoose/Express)

Not able to post data to database and database is not showing in Robo 3T (MongoDB/Mongoose/Express)

我是一名 Web 开发新手(目前处于学习阶段)。

所以,我试图让我的第一个小型后端项目(待办事项应用程序)和 运行 成为数据库问题。

我正在使用 MongoDB 和 Mongoose 作为数据库设置,express 使用 NodeJS 作为后端(使用 ejs 作为模板引擎)。

问题是我无法 post 向数据库添加内容。当我提交表单时出现错误(POST 方法)。

并且在建立连接后,Robo 3T上没有显示。

我不确定我哪里出错了。请帮我解决这个问题。

使用过的文件附在下面。

目录结构

index.js

/** @format */

//requiring express
const express = require("express");

//setting up the port
const port = 1111;

//this module provides a way to work with directories and file paths
const path = require("path");

//requiring configuration for setting up the database to be accessed by mongoose
const db = require("./config/mongoose");

//requiring Task schema/model
//using this we will create entries and populate our collection
const Task = require("./models/task");
const { create } = require("./models/task");

//firing up express
const app = express();

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/assets"));

let task_list = [
    {
        title: "College",
        due_date: "2012-12-13",
        category: "College"
    },
    {
        title: "Home",
        due_date: "2012-12-13",
        category: "Home"
    },
    {
        title: "Work",
        due_date: "2012-12-13",
        category: "Work"
    },
    {
        title: "Group",
        due_date: "2012-12-13",
        category: "Group"
    },
];

app.get("/", function (req, res) {
    Task.find({}, function (err, task) {
        if (err) {
            console.log("Error occured!");
            return;
        }
        return res.render("home", {
            tasks: task
        });
    });
});

app.post("/new-task", function (req, res) {
    console.log(req.body);
    Task.create(
        {
            title: req.body.title,
            due_date: req.body.due_date,
            category: req.body.category
        },
        function (err, newt) {
            if (err) {
                console.log("Error while posting");
                return;
            }
            console.log("Newtask created!: ", newt);
            return res.redirect("back");
        }
    );
});

//creating a listener to the specified port
app.listen(port, function (err) {
    if (err) {
        console.log(`Some error occured at port: ${port}
        Please try again later`);

        return;
    }
    console.log("Yay! Server is running at @ port:", port);
});

注意: 我正在使用 task_list 数组来检查 post 是否正常工作并且它正在工作。但是当我尝试使用持久数据库 (MongoDB) 时出现问题。

mongoose.js(用于连接数据库)

//requiring mongoose to set up connection with database
const mongoose = require('mongoose');

//setting up connection
mongoose.connect('mongodb://localhost:27017/tasks_db', {useNewUrlParser: true, useUnifiedTopology: true});

//to check if the connection is successful or some error occured
const db = mongoose.connection;
db.on('error', console.error.bind(console, "!! Error setting up connection with database !!"));
db.once('open', function() {
    console.log("Connection with database is successful!");
});

task.js(包含模式)

//requiring mongoose
const mongoose = require('mongoose');

//creating the schema for the document of collection
const taskSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    due_data: {
        type: Date,
        required: true,
        get: value => value.toDateString()
    },
    category: {
        type: String,
    }
});

//compiling our schema into a model (a class for interacting with MongoDB) (an instance of model is called a document)
const Task = mongoose.model('Task', taskSchema);
module.exports = Task;

home.ejs(包含视图)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your TO-DO List</title>
    <script src="https://kit.fontawesome.com/fcba9de078.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="/css/style.css" />
</head>

<body class="toggler">
    <!-- The main box containing the list and the form to add or remove item -->
    <div id="todo-box-div" class="flex-row sizi">
        <!-- div containing form for adding items to todo-list -->
        <div id="todo-form-div" class="flex-column sizi">
            <!-- div header -->
            <h1>Do It!</h1>
            <!-- form for adding items -->
            <form action="/new-task" method="POST" id="to-do-form" class="flex-column up-down">
                <input id="title" name="title" class="bottom-b font-4" type="text" placeholder="I have to do this..." required />
                <!-- <textarea id="description" class="bottom-b font-4" type="text"></textarea> -->
                <!-- date and category will be inline for bigger widths -->
                <div id="input-inline" class="flex-row">
                    <input id="date" name="due_date" min="2020-07-20" class="bottom-b font-2" type="date" required />
                    <select id="category" name="category" class="bottom-b font-2 dropdown" type="text">
                        <option value="default" selected disabled>Choose a category</option>
                        <option value="Work">Work</option>
                        <option value="College">College</option>
                        <option value="Home">Home</option>
                        <option value="Group">Group</option>
                    </select>
                </div>
                <!-- button for adding item -->
                <button type="submit" class="font-4" id="add"><i class="fas fa-plus"></i>Add to list</button>
            </form>
        </div>
        <!-- div containing list items (scrollable) and button to delete items -->
        <div id="todo-list-div" class="flex-column sizi">
            <!-- button for deleting items -->
            <button type="submit" class="font-4" id="delete"><i class="far fa-trash-alt"></i>Done</button>
            <!-- list containing todo items -->
            <ul>
                <% for(let a of tasks) { %>
                <li>
                    <div class="list-item">
                        <input type="checkbox" class="pointer" />
                        <div class="name-date font-3">
                            <p><%= a.title %></p>
                            <p><i class="far fa-calendar-alt"></i><%= a.due_date %></p>
                        </div>
                        <div id="redundant"></div>
                        <div class="categ-button font-2 disp"><%= a.category %></div>
                    </div>
                </li>
                <% } %>
            </ul>
        </div>
    </div>
    <script src="/js/script.js"></script>
</body>

</html>

注:表格在todo-box-div下的todo-form-div.

示例错误:

在这里,如果您看到它在提交表单时打印“Error while posting”。 req.body 正在打印。这个错误信息在index.js.

中app.post()方法的错误处理中

我被困了太久,决定在这里 post 并获得一些指导。请帮我解决这个问题。

在 post 方法中尝试以下方法而不是 Task.create(),如果可行请告诉我

const task = new Task({title: "Work",
        due_date: "2012-12-13",
        category: "Work"})
task.save();