T
T
TuMko2021-10-30 17:57:28
Mongoose
TuMko, 2021-10-30 17:57:28

Why are fields not being added to mongodb collection?

I create a backend on node.js, express.js + mongodb (cloud connection).
When requesting to create a new record via Postman (post request to localhost:5000/api/certificate ), only the automatic fields "_id" and "__v" appear, and the fields I specified are not created (it turns out to be added only if you set the default value, in this case value will appear).
What could be the reason?

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;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Test-style, 2021-10-31
@Test-style

Before digging deep, check what you get with a POST request

const certificate = req.body;
console.log('Body: ', certificate)

Maybe it's the method of transferring the load. (Content-type ?) and will need a body-parser

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question