How to target the Database table and save the data into that table?

Viewed 20

I'm trying to create a basic server where there is 2 Api endpoints /users and /users/new. Somehow I managed the Apis to at least run but now I am not able to save the data into the database and also retrieve the database from the database and store it in or somewhere display it . I'm also using mongoose schema based system. Just cant seems to make it work.

database structure is: database_name>table_name to be precise erentals>users

NOTE: I'm also using the latest ES6 module system in Nodejs

index.js aka the base root file :

import mongoose from "mongoose";
import {app} from "./routes.js";
mongoose.connect("mongodb://localhost:27017", {
    serverSelectionTimeoutMS: 5000,
    useNewUrlParser: true
}).catch(err => console.log(err.reason))
// New database connection
const db = mongoose.connection;
db.once("open", function () {
    console.log("Connected Successfully to DB")
})

app.listen(8000, () => console.log("Connected to server."))

routes.js aka where all the routes will go:

import express from "express";
import { user as UserModule } from "./models/user_model.js";
export const app = express();
app.post("/users/new", async (req, res) => {
    const user = new UserModule(req.body);
    try {
        await user.save();
        res.send(user);
    } catch (error) {
        res.status(500).send(error);
    }
})

app.get("/users", async (req, res) => {
    const users = await UserModule.find({});
    try {
        res.send(users);
    } catch (error) {
        res.status(500).send(error);
    }
})

user_model.js aka the user model schema:

import mongoose from "mongoose";

// The format of the user Model
//  Creating a new instance of the mongoose schema class
const userSchema = new mongoose.Schema({
    username: { type: String, required: true },
    gender: { type: String, required: true },
    email: { type: String, required: true },
    phone: { type: Number, min: 10, required: true }
});
export const user = mongoose.model('users', userSchema);

I'm using postman to test the Apis:

/users endpoint:

/user endpoint

/users/new endpoint:

/users/new endpoint

0 Answers
Related