Why does my count route in NodeJS not working? - node.js

const express = require('express')
const Task = require('../models/task-model')
const auth = require('../middleware/auth')
const router = new express.Router()
router.post('/tasks', auth, async (req, res) => {
const task = new Task({
...req.body,
owner: req.user._id
})
try {
await task.save()
res.status(201).send(task)
}
catch (error) {
res.status(400).send(error)
}
})
router.get('/tasks/count', auth, async (req, res) => {
try {
const count = await Task.countDocuments({})
if (!count) {
res.send(404).send()
}
res.send(count)
}
catch (error) {
res.status(500).send(error)
}
})
module.exports = router
Every route except count is working.
I have tried count() function, but it is deprecated.
Now I am using countDocuments({}) but it gives 500 response.
I have tried estimatedDocumentCount() but same response.

Related

message : "Request failed with status code 404" name : "AxiosError"

I've been struggling to make the usersRoute work. I keep getting the error message: "Request failed with status code 404" name: "AxiosError", get request is working but post not - Cannot POST /api/users/register. Could you help me figure this out, please? Thank you
usersRoute code is this:
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
router.post("/login", async(req, res) => {
const {username , password} = req.body
try {
const user = await User.findOne({username , password})
if(user){
res.send(user)
}
else{
return res.status(400).json(error);
}
} catch (error) {
return res.status(400).json(error);
}
});
router.post("/register", async(req, res) => {
try {
const newuser = new User(req.body)
await newuser.save()
res.send('Korisnik uspešno registrovan')
} catch (error) {
return res.status(400).json(error);
}
});
module.exports = router
userAction:
import axios from 'axios'
import {message} from 'antd'
export const userLogin=(reqObj)=>async dispatch=>{
dispatch({type: 'LOADING', payload:true})
try {
const response = await axios.post('/api/users/login', reqObj)
localStorage.setItem('user', JSON.stringify(response.data) )
message.success('Prijava uspela')
dispatch({type: 'LOADING', payload:false})
setTimeout(() => {
window.location.href='/'
}, 500);
} catch(error) {
console.log(error)
message.error('Pokušajte ponovo')
dispatch({type: 'LOADING', payload:false})
}
}
export const userRegister=(reqObj)=> async dispatch =>{
dispatch({type: 'LOADING', payload:true})
try {
const response = await axios.post('/api/users/register' , reqObj)
message.success('Registracija uspela')
setTimeout(() => {
window.location.href='/login'
}, 500);
window.location.href='/login'
dispatch({type: 'LOADING', payload:false})
} catch(error) {
console.log(error)
message.error('Pokušajte ponovo')
dispatch({type: 'LOADING', payload:false})
}
}
server.js:
const express = require('express')
const app = express()
const port = process.env.PORT || 5000
const dbConnection = require('./db')
app.use(express.json())
app.use('/api/cars/', require('./routes/carsRoutes'))
app.use('/api/users/', require('./routes/usersRoute'))
app.get('/', (req,res) => res.send('Hello World'))
app.listen(port, () => console.log(`Node JS Server Started in Post ${port}`))
userModel:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
username : {type:String , required : true},
password : {type:String , required : true}
})
const userModel = mongoose.model('users' , userSchema)
module.exports = userModel
package.json:
"proxy": "http://localhost:5000/"

Heroku route does not work remotely but locally work

Heroku routing does not work
here is my code,
when I deploy my local machine work The Heroku route does not work.
The home route is work but never works on the remote Heroku deployment route
I try to find my problem
tell me what to do
This indicates that the page exists but is producing some sort of error.. Any idea what could be happening? This is a very basic app that I built by reading the Rails Tutorial Book.
import express from "express"
import { MongoClient, ServerApiVersion } from "mongodb"
import { ObjectId } from "mongodb"
import cors from "cors"
import "dotenv/config"
const app = express()
app.use(cors())
app.use(express.json())
const PORT = process.env.PORT || 5000
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#laptopstock.xnbrc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority&ssl=true`
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
})
async function run() {
try {
await client.connect()
const laptopCollection = client.db("laptop_stock").collection("laptops")
app.post("/product", async (req, res) => {
const products = req.body
// console.log(products)
const NewProducts = await laptopCollection.insertOne(products)
res.send(products)
})
// get products
app.get("/product", async (req, res) => {
const query = {}
const cursor = laptopCollection.find(query)
const loadData = await cursor.toArray()
// console.log(loadData)
res.send(loadData)
})
app.get("/product/:id", async (req, res) => {
const id = req.params.id
const query = { _id: ObjectId(id) }
const service = await laptopCollection.findOne(query)
res.send(service)
})
app.put("/update/:id", async (req, res) => {
const id = req.params.id
const data = req.body
const filter = { _id: ObjectId(id) }
const options = { upsert: true }
const updateDoc = {
$set: {
productName: data.productName,
productQuantity: data.productQuantity,
productImg: data.productImg,
productDescription: data.productDescription,
productSeller: data.productSeller,
},
}
const updateProduct = await laptopCollection.updateOne(
filter,
updateDoc,
options,
)
res.send(updateProduct)
})
app.delete("/product/:id", async (req, res) => {
const id = req.params.id
const query = { _id: ObjectId(id) }
const deleteLaptop = await laptopCollection.deleteOne(query)
res.send(deleteLaptop)
})
} catch (error) {
console.log({ massage: error })
}
}
app.get("/", (req, res) => {
res.send({ message: "success" })
})
run()
app.listen(PORT, () => {
console.log("server is running port", PORT)
})

How can I make a post request inside another request using node js, express

I made an application to make push notifications and I succeeded in sending notifications. But I have a problem, which is that I want to save any notification that I send in my database,
Here is the code,
var FCM = require("fcm-node");
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const app = express();
app.use(express.json());
const notificationSchema = mongoose.Schema({
name: String,
});
const NotificationModel = mongoose.model("Notification", notificationSchema);
app.post("/fcm", async (req, res, next) => {
try {
let fcm = new FCM(process.env.SERVER_KEY);
let message = {
to: req.body.token,
notification: {
title: req.body.title,
body: req.body.body,
},
};
fcm.send(message, function (err, response) {
if (err) {
next(err);
} else {
// res.json(response);
// res.send(message.notification.body);
app.post("/notfs", async (req, res) => {
let newNotf = new NotificationModel({
name: message.notification.body,
});
newNotf = await newNotf.save();
res.send(newNotf);
});
}
});
} catch (error) {
next(error);
}
});
app.get("/notfs", async (req, res) => {
const notfs = await NotificationModel.find();
res.send(notfs);
});
mongoose
.connect(process.env.CONNECTION_STRING)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err);
});
app.listen(3000, () => {
console.log("listened");
});
Why doesn't it save notifications in the database?
Another question
Please if there is a better way than this please leave it and thank you٫
Thanks in advance
use axios package, which is recommended by nodejs official.
Its simple like jquery ajax call

Problems with Express's functions using Angular

I am making an app that saves and shows books to sell. It's everything ok, but this error began to appear:
GET http://localhost:3000/api/usuarios 404 (Not Found) zone-evergreen.js:2952
This error appears in two files: 'apuntes' and 'usuarios'
Here is the controller's code:
const usu = require('../models/usuario')
const usuarioCtrl = {};
usuarioCtrl.getUsuarios = async (req, res) => {
const usuarios = await usu.find();
res.json(usuarios);
}
usuarioCtrl.createUsuarios = async (req, res) => {
console.log(req.body);
const usuario = new usu({
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha: req.body.fecha,
registro: req.body.registro,
password: req.body.password
});
await usuario.save();
res.json({
'status': 'Usuario Creado'
});
}
usuarioCtrl.getUsuario = async (req, res) => {
const usuarios = await usu.findById(req.params.id);
res.json(usuarios);
}
usuarioCtrl.editUsuario = async (req, res) => {
const { id } = req.params;
const usuario = {
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha: req.body.fecha,
registro: req.body.registro,
password: req.body.password
};
await usu.findByIdAndUpdate(id, { $set: usuario }, { new: true });
res.json({ status: 'Usuario Actualizado' });
};
usuarioCtrl.deleteUsuario = async (req, res) => {
await usu.findByIdAndRemove(req.params.id);
res.json({ status: 'Usuario Borrado' });
}
module.exports = usuarioCtrl;
I'm sure that the index and route's code are right, but I don't know what to do and why this is happening. I have two controllers and two routes files and both have the same logic.
This is my first question in StackOverflow, I thank you for your help. If you need more details about the project, please tell me.
Here's the router:
const express=require('express');
const router1 = express.Router();
const ctrl1=require('../controllers/usuarios.controller');
router1.get('/', ctrl1.getUsuarios );
router1.post('/',ctrl1.createUsuarios);
router1.get('/:id',ctrl1.getUsuario);
router1.put('/:id',ctrl1.editUsuario)
router1.delete('/:id',ctrl1.deleteUsuario);
module.exports=router1;

Resolving UnhandledPromiseRejectionWarning in express post request

I am trying to make a post request to the server (mongodb) but I get this error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'todo_description' of undefined
I am running mongodb on my localhost
// Require Express
const express = require("express");
// Setting Express Routes
const router = express.Router();
// Set Up Models
const Todo = require("../models/todo");
// Get All Todos
router.get("/", async (req, res) => {
try {
const todo = await Todo.find();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.get("/:id", async (req, res) => {
try {
const id = req.params.id;
await Todo.findById(id, (err, todo) => {
res.json(todo);
});
} catch (err) {
res.json({ message: err });
}
});
router.post("/add", async (req, res) => {
const todo = new Todo({
todo_description: req.body.todo_description,
todo_responsible: req.body.todo_responsible,
todo_priority: req.body.todo_priority,
todo_completed: req.body.todo_completed,
});
try {
await todo.save();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.patch("/update/:id", async (req, res) => {
try {
const updateTodo = await Todo.updateOne(
{ _id: req.params.id },
{ $set: { todo_description: req.body.todo_description } }
);
updateTodo.save().then(updateTodo => {
res.json(updateTodo);
});
} catch (err) {
res.json({ message: err });
}
});
router.delete("/delete/:id", async (req, res) => {
try {
const deleteTodo = await Todo.deleteOne({ _id: req.params.id });
res.json(deleteTodo);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
my todo model
// Require Mongoose
const mongoose = require("mongoose");
// Define Schema
// const Schema = new mongoose.Schema;
// Define Todo-Schema
const TodoSchema = new mongoose.Schema({
// Creating Fields
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
},
todo_date: {
type: Date,
default: Date.now
}
});
// Compile Model From Schema
// const TodoModel = mongoose.model("Todos", TodoSchema);
// Export Model
module.exports = mongoose.model("todos", TodoSchema);
error message:
(node:548) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'todo_description' of undefined
at router.post (C:\Users\kinG\Desktop\projects\mountain-of-prototype\mern\backend\routes\todo.js:33:32)
at Layer.handle [as handle_request] (C:\Users\kinG\Desktop\projects\mountain-of-prototype\mern\backend\node_modules\express\lib\router\layer.js:95:5)
thank you
You are accessing todo_description from req.body. req.body will only be available if you add the body-parser middleware or add a similar one yourself.
Add this right before your routes are loaded :
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
You can also add this to a specific route. Read more about it here.
You should use body-parser in your master file of the application. Which gives you the parsed json before your middle-ware parse the body, which by-default in string. And also make sure you are sending todo_description in the req.body(should check before use).
const bodyParser = require('body-parser');
app.use(bodyParser.json());

Resources