Home > Software engineering >  Node express API using class not inserting data
Node express API using class not inserting data

Time:12-26

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

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;

CodePudding user response:

Refactor the create method like so.

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

const savedItem = await ItemToSave.save();

return res.status(201).send(savedItem);
  • Related