MEAN STACK : In my app, database is created but collections are not updated it is showing empty?

29 Views Asked by At

I am beginner in MEAN stack development, I have some problem related with database.

In my app, database is created but collections are showing empty, when I have created user Model it was showing only user data. Then i did drop database and again run app then it is showing nothing. what is the problem in it.No error also

database image

Here is my code:

database.config.ts

import mongoose, { ConnectOptions } from "mongoose";

export const dbConnect = () => {
    mongoose.connect("mongodb://127.0.0.1:27017/foodmineDB", {
        useNewUrlParser : true,
        useUnifiedTopology :true
    } as ConnectOptions).then(
        () => console.log("connect success"),
        
    ).catch((error) => {
        console.log(error);
    })
}

server.ts

import dotenv from "dotenv";
dotenv.config();
import express from "express";
import cors from "cors";
import foodRouter from "./routers/food.router"
import userRouter from "./routers/user.router"
import orderRouter from "./routers/order.router"
import { dbConnect } from "./configs/database.config";
dbConnect();


const app = express();
app.use(express.json());
app.use(cors({
    credentials: true,
    origin : ["http://localhost:4200"]
}) );
app.use("/api/foods", foodRouter);
app.use("/api/users", userRouter);
app.use("/api/orders", orderRouter);


const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log("Website served on http://localhost:" + port);
})

data.ts

export const sample_foods: any[] = [
  {
    id:'1',
    name: 'Pizza Pepperoni',
    cookTime: '10-20',
    price: 10,
    favorite: false,
    origins: ['italy'],
    stars: 4.5,
    imageUrl: 'assets/food-1.jpg',
    tags: ['FastFood', 'Pizza', 'Lunch'],
  },
  {
    id:'2',
    name: 'Meatball',
    price: 20,
    cookTime: '20-30',
    favorite: true,
    origins: ['persia', 'middle east', 'china'],
    stars: 4.7,
    imageUrl: 'assets/food-2.jpg',
    tags: ['SlowFood', 'Lunch'],
  }
]

export const sample_tags:any[] = [
  { name: 'All', count: 6 },
  { name: 'FastFood', count: 4 },
  { name: 'Pizza', count: 2 },
  { name: 'Lunch', count: 3 },
  { name: 'SlowFood', count: 2 },
  { name: 'Hamburger', count: 1 },
  { name: 'Fry', count: 1 },
  { name: 'Soup', count: 1 },

]

export const sample_users: any[] = [
  {
    name: "John Doe",
    email: "[email protected]",
    password: "12345",
    address: "Toronto On",
    isAdmin: true,
  },
  {
    name: "Jane Doe",
    email: "[email protected]",
    password: "12345",
    address: "Shanghai",
    isAdmin: false,
  },
];

food.model.ts

import {Schema, model} from 'mongoose';

export interface Food{
    id:string;
    name:string;
    price:number;
    tags: string[];
    favorite:boolean;
    stars: number;
    imageUrl: string;
    origins: string[];
    cookTime:string;
}

export const foodSchema = new Schema<Food>(
    {
        name: {type: String, required:true},
        price: {type: Number, required:true},
        tags: {type: [String]},
        favorite: {type: Boolean, default:false},
        stars: {type: Number, required:true},
        imageUrl: {type: String, required:true},
        origins: {type: [String], required:true},
        cookTime: {type: String, required:true}
    },{
        toJSON:{
            virtuals: true
        },
        toObject:{
            virtuals: true
        },
        timestamps:true
    }
)

export const FoodModel = model<Food>('Food', foodSchema);

food.router.ts

import { Router } from "express";
import asyncHandler from "express-async-handler";
import { sample_foods, sample_tags } from "../data";
import { FoodModel } from "../models/food.model";

const router = Router();

router.get("/seed",asyncHandler(
    async (req,res) => {
        const foodCount = await FoodModel.countDocuments();
        if(foodCount > 0) {
            res.send("Seed is already done!");
            return;
        }
        await FoodModel.create(sample_foods);
        res.send("seed is done!");
    })
)

router.get("/", asyncHandler(
    async (req,res) => {
        const foods =  await FoodModel.find();
        res.send(foods);
    }
))

router.get("/search/:searchTerm",asyncHandler(
    async (req, res) => {
      const searchRegex = new RegExp(req.params.searchTerm, 'i');
      const foods = await FoodModel.find({name: {$regex:searchRegex}})
      res.send(foods);
    }
  ))
  
  router.get("/tags", asyncHandler(
    async (req, res) => {
      const tags = await FoodModel.aggregate([
        {
          $unwind:'$tags'
        },
        {
          $group:{
            _id: '$tags',
            count: {$sum: 1}
          }
        },
        {
          $project:{
            _id: 0,
            name:'$_id',
            count: '$count'
          }
        }
      ]).sort({count: -1});
  
      const all = {
        name : 'All',
        count: await FoodModel.countDocuments()
      }
  
      tags.unshift(all);
      res.send(tags);
    }
  ))
  
router.get("/tag/:tagName", asyncHandler(
  async (req,res) => {
    const foods = await FoodModel.find({tags: req.params.tagName})
    res.send(foods);
  })
);

router.get("/:foodId", 
async (req,res) => {
  const food = await FoodModel.findById(req.params.foodId)
    res.send(food);
});

export default router;
0

There are 0 best solutions below