我目前正在做一个关于笔记应用的项目。在此之前,我只了解有关在 mongodb 中处理一个集合的知识。但在这个应用程序中,我尝试创建用户可以添加注释,将该注释添加到首选类别。在此过程中,用户可以选择首选类别。(一般,待办事项)..而且用户也可以创建自己的新类别。当用户创建新类别时,它会将其保存在数据库中,并显示已创建的类别(存储在数据库中)。
我创建了路线和开发数据库。一切工作正常。注释已创建。
//服务器.js
//other mongo db connections
app.use('/note', NoteRoutes)
app.use('/category', CategoryRoutes)
//NoteRoute.js
const express = require('express');
const router = express.Router();
const { getAllNoteData, getOneNoteData, addNewNote, updateNote, deleteNote } = require('../controller/noteController.js');
//routes for get all Note Data
router.get('/', getAllNoteData)
//routes for get specific Data
router.get('/:id', getOneNoteData)
//routes for add new note
router.post('/', addNewNote)
//update the exsist note
router.put('/:id', updateNote)
//delete the exsist note
router.delete('/:id', deleteNote)
//export rounter
module.exports = router;
//categoryRoute.js
const express = require('express');
const router = express.Router();
const { getCategory, createCategory } = require('../controller/categoryController.js');
//create new category
router.post('/category', createCategory)
//get all categories
router.get('/category', getCategory)
//export rounter
module.exports = router;
//noteController.js
//imported required modules
const mongoose = require('mongoose')
const Note = require("../models/notemodels")
const Category = require("../models/category")
//get all notes from db
const getAllNoteData = async(req, res) => {
try {
//all data assign to notes variable and sort by created date
const notes = await Note.find({}).sort({ createdAt: -1 })
//return success response and pass data and number of notes using JSON format
return res.status(200).json({
count: notes.length,
data: notes
})
} catch (error) {
//error handling
return res.status(500).json({ message: error.message });
}
}
//get specific note based on id
const getOneNoteData = async(req, res) => {
const { id } = req.params;
try {
//find the note by id and assign it into notes variable if requested data exsist
const notes = await Note.findById({ _id: id })
//if no data found then send not found status else pass success status
if (!notes) {
return res.status(400).json({ message: "No user found" });
} else {
return res.status(200).json(notes);
}
} catch (error) {
//error handling
return res.status(500).json({ message: error.message });
}
}
//add new note
const addNewNote = async(req, res) => {
try {
const { title, content, category } = req.body;
if (!title || !content) {
return res.status(400).send({ message: "Please fill out all input fields" })
}
let categoryObj = await Category.findOne({ name: category });
if (!categoryObj) {
categoryObj = new Category({ name: category });
await categoryObj.save();
}
const newNote = {
title: req.body.title,
content: req.body.content,
category: categoryObj._id
}
const note = await Note.create(newNote)
return res.status(200).send({ data: note, message: "New Note added successfully" })
} catch (error) {
return res.status(500).json({ message: error.message });
}
}
//update exsist note
const updateNote = async(req, res) => {
try {
if (!req.body.title || !req.body.content) {
return res.status(400).send("Complete all the empty spaces")
}
const { id } = req.params;
const note = await Note.findByIdAndUpdate(id, req.body);
if (!note) {
return res.send("No such note found!").status(400)
} else {
return res.send("Update Completed Successfully!").status(400)
}
} catch (error) {
return res.status(500).json({ message: error.message });
}
}
const deleteNote = async(req, res) => {
try {
const { id } = req.params;
const delNote = await Note.findByIdAndDelete(id);
if (!delNote) {
return res.status(400).send("No Note Found with this ID");
} else {
return res.status(200).send("Note Deleted Successfully")
}
} catch (error) {
return res.status(500).json({ message: error.message })
}
}
//export the functions
module.exports = { getAllNoteData, getOneNoteData, addNewNote, updateNote, deleteNote }
//类别controller.js
const mongoose = require('mongoose')
const Category = require("../models/category")
const getCategory = async(req, res) => {
try {
const categories = await Category.find({}).sort({ createdAt: -1 });
return res.status(200).json(categories);
} catch (error) {
console.error('Error fetching categories:', error);
console.error('Error details:', error.message); // Log error message
return res.status(500).send({ message: 'Internal Server Error' });
}
};
//create new category
const createCategory = async(req, res) => {
try {
const { name } = req.body;
let category = await Category.findOne({ name });
if (!category) {
category = new Category({ name });
await category.save();
} else {
return res.status(400).json({ message: 'Category already exists' });
}
res.status(201).json(category);
} catch (error) {
res.status(500).json({ message: 'Server Error' });
}
}
module.exports = { getCategory, createCategory };
在这里,当我创建注释对象时,它创建得很好并像这样显示
{
"_id": "65fc8105c24e467d7397f3b4",
"title": "Make coffie",
"content": "use today to it",
"color": "white",
"category": "65fc7dcc97c1e426998de3f7", //category object
"createdAt": "2024-03-21T18:48:37.866Z",
"updatedAt": "2024-03-21T18:48:37.866Z",
"__v": 0
}
它还创建了对象 id。这意味着它创建的某个地方。
但是当我尝试查看类别时,它显示了这个
http://localhost:3000/category
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /category</pre>
</body>
</html>
但是当我添加这个时它会显示这个
http://localhost:3000/note/category
{
"message": "Cast to ObjectId failed for value \"{ _id: 'category' }\" (type Object) at path \"_id\" for model \"Note\""
}
有人可以帮我学习这个吗?
当您在此处安装第二个路由器时:
app.use('/category', CategoryRoutes)
CategoryRoutes
隐式内的所有路线均以/category
开头。
所以这些路线的前缀是
/category
:
router.post('/category', createCategory);
// Translates to http://localhost:3000/category/category
router.get('/category', getCategory)
// Translates to http://localhost:3000/category/category
您需要将它们更改为:
//create new category
router.post('/', createCategory)
// Translates to http://localhost:3000/category
//get all categories
router.get('/', getCategory)
// Translates to http://localhost:3000/category
这解释了为什么您会收到
Cannot GET /category
,因为您的路由器中不存在该路由。
在第二个示例中,当您发出
GET
请求时:
http://localhost:3000/note/category
Express 将请求发送至此处:
app.use('/note', NoteRoutes)
然后这里:
//routes for get specific Data
router.get('/:id', getOneNoteData)
它假定单词
category
是 :id
参数,并尝试将单词 category
转换为 ObjectId
函数中的 getOneNoteData
,但显然不能,因为 category
不是可转换值。