【发布时间】:2020-01-26 14:58:03
【问题描述】:
我正在尝试使用 mongoose/express 将表单数据添加到数据库。该集合是在数据库中创建的,尽管提交时没有错误,并且我的 console.log 确认数据存在以及生成的 ID 我在数据库中仍然没有任何条目,你能看到我在做什么失踪?任何帮助将不胜感激。
**CONFIG**
const port = process.env.PORT || 3000,
bodyparser = require("body-parser"),
mongoose = require("mongoose"),
express = require("express"),
app = express();
app.set("view engine", "ejs");
app.use(
bodyparser.urlencoded({
extended: true
})
);
app.use(
require("express-session")({
secret: "Mama Mia Thats a Spicy Meatball!",
resave: false,
saveUninitialized: false
})
);
app.use(express.static(__dirname + "/styles/"));
app.use(express.static(__dirname + "/Media/"));
app.use(express.static(__dirname + "/JS/"));
mongoose.connect("mongodb://localhost/lashB", {
useNewUrlParser: true
});
const mongCon = mongoose.connection;
mongCon.on("connected", function () {
console.log(`beep boop
database mainframe syncroniiiiiiized`);
});
mongCon.on("disconnected", function () {
console.log(`You're off the database now...Daniel San.`);
});
mongCon.on('error', function () {
console.log(error, `We've got company...there's an error!!!`);
});
**SCHEMA**
var customerSchema = new mongoose.Schema({
firstName: String,
lastName: String,
mobile: String,
email: String,
treatment: String,
time: String,
date: Date
});
var Customer = mongoose.model("Customer", customerSchema, "Customer");
**ROUTES**
app.get("/", function (req, res) {
res.render("main");
});
app.get("/appointment", function (req, res) {
res.render("appointment");
});
app.get("/appointmentConfirmation", function (req, res) {
res.render("appConfirmation");
});
app.get("/blogHome", function (req, res) {
res.render("blogHome");
});
app.post('/appointment', function (req, res) {
var firstName = req.body.firstName,
lastName = req.body.lastName,
mobile = req.body.mobile,
email = req.body.email,
treatment = req.body.treatment,
time = req.body.time,
date = req.body.date;
var deetz = {
date: date,
time: time,
treatment: treatment,
email: email,
mobile: mobile,
firstName: firstName,
lastName: lastName
}
Customer.create(deetz, function (err, info) {
if (err) {
console.log(err, `something went wrong`);
} else {
console.log(info);
console.log('newly created file for a customer');
}
});
res.render('appConfirmation', {
firstName: firstName
}
);
});
app.listen(port, function () {
console.log(`You rockin' now on port ${port}`);
});
【问题讨论】:
-
看起来不错,您可能需要重新加载数据库才能查看新结果
-
@AnkitManchanda 我重新加载到 db 但不高兴,我什至尝试使用 insertOne 方法,我的控制台确认数据已发送并分配了一个 ID,但是当我检查猫鼬时,我什么都没有
-
因此,如果我使用 Compass GUI,数据就会存在,但在 shell 中绝对没有,有人有什么想法吗?我正在输入 show dbs > use nameofdb > show collections > use nameofcollection > db.nameofcollection.find - 但什么也没有
标签: mongodb express mongoose mongoose-schema