Создаю backend на node.js, express.js + mongodb (облачное подключение).
При запросе на создание новой записи через Postman (post запрос на
localhost:5000/api/certificate) появляются только автоматические поля "_id" и "__v", а указанные мною поля не создаются (получается добавить только если задавать значение default, в таком случае появится значение).
В чем может быть причина?
app.js
const config = require("config");
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const PORT = config.get("port") || 5000;
const URI = config.get("mongoUri");
//middlewares
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//routes prefix
app.use("/api/certificate", require("./routes/routes"));
async function start() {
try {
//connect to database
await mongoose
.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connecting to the database!"))
.catch((err) => console.log(err));
// start server
app.listen(PORT, () =>
console.log(`App has been started on port ${PORT}...`)
);
} catch (e) {
console.log("Server Error:", e.message);
process.exit(1);
}
}
start();
models/Certificate.js
const mongoose = require("mongoose");
const certificateSchema = mongoose.Schema({
title: { type: String },
category: String,
content: String,
created: {
type: Date,
// default: Date.now
},
});
module.exports = mongoose.model("Certificate", certificateSchema);
controllers/api.js
const Certificate = require("../models/Certificate");
module.exports = class API {
//fetch all certificates
static async fetchAllCertificates(req, res) {
try {
const certificates = await Certificate.find();
res.status(200).json(certificates);
} catch (err) {
res.status(404).json({ message: err.message });
}
}
//fetch certificates by ID
static async fetchCertificatesByID(req, res) {
res.send("by id");
}
//create a certificate
static async createCertificate(req, res) {
const certificate = req.body;
try {
await Certificate.create(certificate);
res.status(201).json({ message: "Certificate created successfully!" });
} catch (err) {
res.status(400).json({ message: err.message });
}
}
//update a certificate
static async updateCertificate(req, res) {
res.send("update");
}
//delete a certificate
static async deleteCertificate(req, res) {
res.send("del");
}
};
routes/routes.js
const express = require("express");
const router = express.Router();
const API = require('../controllers/api');
router.get("/", API.fetchAllCertificates);
router.get("/:id", API.fetchCertificatesByID);
router.post("/", API.createCertificate);
router.patch("/:id", API.updateCertificate);
router.delete("/:id", API.deleteCertificate);
module.exports = router;