我正在学习一个教程,我正在研究它的最后一部分.我试图通过一个'PUT'请求覆盖数据库的内容。
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB", {useNewUrlParser: true});
const articleSchema = {
title: String,
content: String
};
const Article = mongoose.model("Article", articleSchema);
// Requests Targeting All Routes
app.route("/articles")
.get(function(req, res) {
Article.find()
.then((foundArticles) => {
mongoose.connection.close();
foundArticles.forEach(function(foundArticle) {
// console.log(foundArticle);
res.send(foundArticles);
})
})
.catch(function(err) {
console.log(err);
})
})
.post(function(req, res) {
const newArticle = new Article({
title: req.body.title,
content: req.body.content
});
newArticle.save()
.then(function() {
res.send("Successfully added a new article.");
})
.catch(function(err) {
console.log(err);
})
})
.delete(function(req, res) {
Article.deleteMany()
.then(() => {
res.send("Successfully deleted the document.");
})
.catch(function(err) {
console.log(err);
})
});
// Requests Targeting Specific Routes
app.route("/articles/:articleTitle")
.get(function(req, res) {
const title = req.params.articleTitle;
Article.find({title})
.then((foundArticle) => {
res.send(foundArticle);
})
.catch(function(err) {
console.log(err);
})
})
// It won't allow the contents of the database to be overwritten.
.put(function(req, res) {
Article.replaceOne({ title: req.params.articleTitle },
{
title: req.body.title,
content: req.body.content,
})
.then(() => {
res.send("Successfully updated article.");
})
.catch(function(err) {
console.log(err);
})
})
app.listen(3000, function() {
console.log("Server started on port 3000!");
});
数据库的内容采用以下格式:
{
"_id" : ObjectId("6517a22854d8425f4e613d9e"),
"title" : "REST",
"content" : "REST is short for REpresentational State Transfer. It's an architectural style for designing APIs."
}
我在Postman中尝试了这个,没有错误。但问题是数据库的内容没有更新。由于没有显示错误,因此很难找出问题所在。
1条答案
按热度按时间xt0899hw1#
更新文档需要使用
updateOne
API。参考
https://mongoosejs.com/docs/api/model.html#Model.updateOne()