Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node express API using class not inserting data

Newbie in Node js, I am using Node JS to build APIs and using class. There are 2 routes till now, one is to fetch all users which is working fine, another is to insert new user which is not working. It is returning {} with status 500.

Here are the files.

index.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import server from "./config/server.js";
import './config/database.js';

const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
  console.log(`app running on port ${PORT}`);
});

config/database.js

import mongoose from "mongoose";

class Connection {
  constructor() {
    const url =
      process.env.MONGODB_URI || `mongodb://localhost:27017/dev-muscles`;
    console.log("Establish new connection with url", url);
    mongoose.Promise = global.Promise;
    // mongoose.set("useNewUrlParser", true);
    // mongoose.set("useFindAndModify", false);
    // mongoose.set("useCreateIndex", true);
    // mongoose.set("useUnifiedTopology", true);
    mongoose.connect(url);
  }
}

export default new Connection();

config/server.js

    import express from "express";
    import UserController from "../src/models/controllers/UserController.js";

    const server = express();
    server.use(express.json());

    server.get(`/users`, UserController.getAll);
    server.post(`/users/create`, UserController.create);


    export default server;

src/models/User.js

import mongoose from "mongoose";
const { Schema } = mongoose;
import validator from "validator";

class User {
    initSchema() {
        const schema = new Schema({
            first_name: {
                type: String,
                required: true,
                trim: true
            },
            last_name: {
                type: String,
                required: true,
                trim: true
            },
            email: {
                type: String,
                required: true,
                trim: true,
                lowercase: true,
                // validate(value) {
                //     if( !validator.isEmail(value) ) {
                //         throw new Error('Email is invalid')
                //     }
                // }
            },
            phone: {
                type: Number,
                required: true,
                trim: true
            },
            password: {
                type: String,
                required: true
            }
        });
        
        // schema.plugin(validator);
        mongoose.model("users", schema);
    }

    getInstance() {
        this.initSchema();
        return mongoose.model("users");
    }
}

export default User;

src/controllers/UserController.js

import Controller from "./Controller.js";
import User from ".././models/User.js";
const userModelInstance = new User().getInstance();

class UserController extends Controller {

    constructor(model) {
        super(model);
    }
}

export default new UserController(userModelInstance);

src/controllers/Controller.js

class Controller {

    constructor(model) {
        this.model = model;
        this.getAll = this.getAll.bind(this);
        this.create = this.create.bind(this);
    }

    async getAll(req, res) {    // works fine
        return res.status(200).send(await this.model.find({}));
    }

    async create(req, res) {    // this is returning {} with status code 500
        try {
            // return res.send(req.body);
            return res.status(201).send(await new this.model.save(req.body));
        } catch (error) {
            res.status(500).send(error);
        }
        
    }

}

export default Controller;

>Solution :

Refactor the create method like so.

const ItemToSave = new this.model(req.body); 

const savedItem = await ItemToSave.save();

return res.status(201).send(savedItem);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading