【发布时间】:2020-08-08 15:03:48
【问题描述】:
我的 Mongoose 代码位于单独的 model.js 文件中,而用于处理 http 请求的 Express 代码位于 app.js 中。我只是在为一个虚构的 wiki 文章站点练习创建 API 并在 Postman 上对其进行测试。我正在努力让它工作的 api 正在删除一篇文章。 (注意:为简洁起见,我只包含了有问题的代码,即来自app.js的app.delete('/articles/:id' ....,以及它从model.js调用的静态方法-deleteOneArticleFromDB(articleID)
app.js:
const express = require('express');
const bodyParser = require('body-parser');
const model = require('./model');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.delete('/articles/:id', async (req, res) => {
const articleID = req.params.id;
console.log(`req.params.id: ${req.params.id}`);
try {
const response = await model.DBUtility.deleteOneArticleFromDB(articleID);
res.status(200).json({message: response, app: 'wiki-api'});
} catch (err) {
res.json({message: err, app: 'wiki-api'});
}
});
const port = 3000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
model.js:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/wikiDB', {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });
const articleSchema = new mongoose.Schema({
title: String,
content: String
});
const Article = mongoose.model('Article', articleSchema);
class DBUtility {
static deleteOneArticleFromDB(articleID) {
return new Promise((resolve, reject) => {
Article.findByIdAndDelete(articleID, (err) => {
if (err) {
reject(err);
} else {
resolve(`Deleted article ${articleID} successfully`);
}
});
});
}
}
exports.DBUtility = DBUtility;
我的数据库中有 5 篇文章(5 个文档):
{
"_id" : "5c139771d79ac8eac11e754a",
"title" : "API",
"content" : "API stands for Application Programming Interface. It is a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components. A good API makes it easier to develop a computer program by providing all the building blocks, which are then put together by the programmer."
}
/* 2 */
{
"_id" : "5c1398aad79ac8eac11e7561",
"title" : "Bootstrap",
"content" : "This is a framework developed by Twitter that contains pre-made front-end templates for web design"
}
/* 3 */
{
"_id" : "5c1398ecd79ac8eac11e7567",
"title" : "DOM",
"content" : "The Document Object Model is like an API for interacting with our HTML"
}
/* 4 */
{
"_id" : "5ea2c188fa57aa1b6453eda5",
"title" : "Node JS",
"content" : "Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a web browser. Node.js lets developers use JavaScript to write command line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Consequently, Node.js represents a \"JavaScript everywhere\" paradigm,[6] unifying web-application development around a single programming language, rather than different languages for server- and client-side scripts.",
"__v" : 0
}
/* 5 */
{
"_id" : "5ea2d5304e19b11e0013a86a",
"title" : "EJS",
"content" : "EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. No religiousness about how to organize things. No reinvention of iteration and control-flow. It's just plain JavaScript",
"__v" : 0
}
我正在尝试删除标题为EJS 的最后一篇文章(文档)。所以在 Postman 中,我按如下方式运行 http 请求:
如您所见,我得到了成功响应。但是,当我检查我的数据库时,该文档仍然存在(我已经单击了几次刷新并使用 GET 请求返回所有文章进行了测试,结果表明该文章仍然存在):
这是终端输出:
[nodemon] starting `node app.js`
Server started on port 3000
req.params.id: 5ea2d5304e19b11e0013a86a
我已经做了两天了。我已经检查了所有以前与我的标题相似的 SO 帖子,但我看不到适用于我的问题的帖子。我不明白我要去哪里错了!!任何帮助将不胜感激。
更新
根据 Mohammed Yousry 下面的解决方案,我意识到我使用字符串手动添加了 _id 字段,因为我正在按照教程进行操作。因此不允许 MongoDB 创建 _id 字段,而是作为 ObjectId。因此,我的 _id 字段的类型是 String 而不是 ObjectId。因此,为了解决这个问题,我从数据库中删除了所有文档并重新添加它们,使用 POSTMAN 和我创建的 POST 方法 - 用于向数据库创建/添加新文章文档,仅提供 title 和 content 字段在请求正文中。因此允许 MongoDB 为每个文章文档创建 _id 字段。现在在数据库中_id 字段的类型为ObjectId。这仍然没有完全解决我的问题,但它更进一步。仍在努力达成解决方案。请参考下面解决方案部分的讨论。
【问题讨论】:
标签: node.js mongodb express mongoose