我一直在使用 mongoose 使用 express 和 mongoDB 開發 CRUD 應用程式,由于某種原因,在模型架構上創建的所有資料都沒有反映在 MongoDB 上。我不確定我出了什么問題,但我要求有人幫助我解決為什么在模型上創建的資料沒有顯示在 mongoDB 中,就像我去郵遞員并執行 http://localhost:5001/jobs 的 get 方法一樣我的輸出如下所示。下面還有我的所有檔案,以獲取您的指導。
使用 post router 在 POSTMAN 上發布的示例資料:
{
"username": "test",
"job_title": "DevOps",
"job_comp_image": "https://pixabay.com/images/id-1869401/",
"job_comp_name": "Training Academy",
"job_description":"Web Developer",
"job_location": "City",
"job_field": "IT",
"job_closing_date": "2021-11-07T04:11:08.924Z",
"job_date_created" : "2021-11-07T04:11:08.924Z"
}
POSTMAN GET 示例作業發布后的輸出:
"_id": "618bb690fbef67502a29854b",
"username": "test",
"job_closing_date": "2021-11-10T12:09:52.427Z",
"job_date_created": "2021-11-10T12:09:52.427Z",
"createdAt": "2021-11-10T12:09:52.428Z",
"updatedAt": "2021-11-10T12:09:52.428Z",
"__v": 0
作業模型.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const jobsiteSchema = new Schema ({
username: String,
job_title: String ,
job_comp_image: String,
job_comp_name: String,
job_description: String,
job_location: String,
job_field: String ,
job_closing_date: { type: Date, default: Date.now},
job_date_created: { type: Date, default: Date.now },
}, {
timestamps: true,
});
const Job = mongoose.model("Job", jobsiteSchema) ;
module.exports = Job;
作業.js
const router = require('express').Router();
let Job = require('../models/jobs.model');
router.route('/').get((req, res) => {
Job.find()
.then(jobs => res.json(jobs))
.catch(err => res.status(400).json('Error: ' err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const jobTitle = req.body.job_title;
const JobCompImage = req.body.job_comp_image;
const JobCompName = req.body.job_comp_name;
const JobDescription = req.body.job_description;
const JobLocation = req.body.job_location;
const JobField = req.body.job_field;
const JobClosingDate = req.body.job_closing_date ;
const JobPostingDate = Date.parse(req.body.job_date_created) ;
console.log(username)
console.log(jobTitle)
console.log(JobCompImage)
console.log(JobCompName)
console.log(JobDescription)
console.log(JobLocation)
console.log(JobField)
console.log(JobClosingDate)
console.log(JobPostingDate)
// Create new Job using the fields above
const newJob = new Job({
username:username,
jobTitle : jobTitle,
JobCompImage : JobCompImage,
JobCompName: JobCompName,
JobDescription: JobDescription,
JobLocation: JobLocation,
JobField : JobField,
JobClosingDate : JobClosingDate,
JobPostingDate : JobPostingDate
});
//Save the new Job
newJob.save()
.then(() => res.json('Job added!'))
.catch(err => res.status(400).json('Error: ' err));
});
router.route('/:id').get((req, res) => {
Job.findById(req.params.id)
.then(job => res.json(job))
.catch(err => res.status(400).json('Error: ' err));
});
router.route('/:id').delete((req, res) => {
Job.findByIdAndDelete(req.params.id)
.then(() => res.json('Job deleted.'))
.catch(err => res.status(400).json('Error: ' err));
});
router.route('/update/:id').post((req, res) => {
Job.findById(req.params.id)
.then(job => {
// username = req.body.username;
job.jobTitle = req.body.job_title;
job.JobCompImage = req.body.job_comp_image;
job.JobCompName = req.body.job_comp_name
job.JobDescription = req.body.job_description;
job.JobLocation = req.body.job_location;
job.JobField = req.body.job_field;
job.JobClosingDate = req.body.job_closing_date ;
job.save()
.then(() => res.json('Job updated!!!'))
.catch(err => res.status(400).json('Error: ' err));
})
.catch(err => res.status(400).json('Error: ' err));
});
module.exports = router;
服務器.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require("path");
require('dotenv').config();
const app = express();
const jobsRouter = require('./routes/jobs');
const usersRouter = require('./routes/users');
app.use(cors());
app.use(express.json());
// ... other app.use middleware
app.use(express.static(path.join(__dirname, "backend", "build")));
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,
{ useNewUrlParser: true,
//useCreateIndex: true,
useUnifiedTopology: true
}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.use('/jobs', jobsRouter);
app.use('/users', usersRouter);
const port = process.env.PORT || 5001;
// Right before your app.listen(), add this:
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "backend", "build", "index.html"));
});
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
})
uj5u.com熱心網友回復:
這是由于錯誤的變數名稱:您的架構在下劃線大小寫中定義了變數名稱,并且您在 MongoDB 中以駝峰命名方式傳遞資料。
作為username匹配,您將存盤該值。所有時間戳都有默認值,因此您也可以獲得這些值。
const jobsiteSchema = new Schema ({
username: String,
job_title: String ,
job_comp_image: String,
job_comp_name: String,
job_description: String,
job_location: String,
job_field: String ,
job_closing_date: { type: Date, default: Date.now},
job_date_created: { type: Date, default: Date.now },
}, {
timestamps: true,
})
將您的路由處理程式更改為以下內容:
router.route('/add').post((req, res) => {
const newJob = new Job(req.body);
//Save the new Job
newJob.save()
.then(() => res.json('Job added!'))
.catch(err => res.status(400).json('Error: ' err));
});
在將它存盤到資料庫之前添加對 req 主體的驗證是理想的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355640.html
