MongoDB没有在任何地方保存数据



我是nodejs、mongoose、express的新手,我正在尝试创建一个基本的twitter克隆。当我想创建一条新的推文并点击提交按钮时,什么都不会发生。这是我的代码:


app.js

var     express     = require("express"),
mongoose    = require("mongoose"),
bodyParser  = require("body-parser"),
ejs         = require("ejs");
var app = express();
mongoose.connect("mongodb://localhost:27017/twitter_clone", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("CONNECTED TO DB"))
.catch((error) => console.log(error.message));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));
app.set("view engine", "ejs");
// MONGODB TWEETS SCHEMA
var tweetsSchema =  new mongoose.Schema({
text: String
})
var Tweets = mongoose.model("Tweets", tweetsSchema);
//================
//RESTFUL ROUTES
//================
// INDEX ROUTES
app.get("/", function(req, res){
Tweets.find({}, function(err, allTweets){
if(err){
console.log(err);
} else {
res.render("home", {newtweet:allTweets});
}
})
})
app.get("/explore", function(req, res){
res.render("explore");
})
app.get("/notifications", function(req, res){
res.render("notifications");
})
app.get("/messages", function(req, res){
res.render("messages");
})
app.get("/bookmarks", function(req, res){
res.render("bookmarks");
})
app.get("/lists", function(req, res){
res.render("lists");
})
app.get("/profile", function(req, res){
res.render("profile");
})
app.get("/more", function(req, res){
res.render("more");
})
// NEW ROUTES
app.get("/tweet/new", function(req, res){
res.render("new");
})

// POST
app.post("/posttweet", function(req, res){
var text = req.body;
var newtweet = {textmessage: text};
Tweets.create(newtweet, function(err, newTweet){
if(err){
console.log(err)
} else {
res.redirect("/");
}
})
})



app.listen(5000, function(){
console.log("Server listening on port 5000");
})

home.ejs:
<div class="middlewelcome">
<h3>Welcome to twitter!</h3>
<p id="welcomingp">This is the best place to see what’s happening in your world. Find some people and topics <br> to follow now.</p>
<button id="getstarted" class="bluebutton">Get Started</button>
</div>
<div class="tweets">
<% newtweet.forEach(function(newtweet){ %>
<div class="showtweets">
<h1>
<%= newtweet.text %>
</h1>
</div>
<% }) %>
</div>
</div>

我之前尝试手动保存一个新文本,它运行良好,所以我不知道会出现什么问题,也不知道为什么我的post route不工作

tweetsSchema中,文本字段名为text,但在POST路由中,您将其称为textmessage。尝试重命名POST路由中的值以匹配架构。

app.post("/posttweet", function(req, res){
var text = req.body;
var newtweet = {text: text}; // typo error
Tweets.create(newtweet, function(err, newTweet){
if(err){
console.log(err)
} else {
res.redirect("/");
}
})
})

您定义的架构和正在传递的对象与不匹配

最新更新