app.post connection and middleware in nodejs - node.js

app.post is not working on postman and showing result in not in JSON format and also middleware is showing error in postman what m doing wrong in this??
is there any new middleware code introduced recently??
// importing
import express from "express";
import mongoose from "mongoose";
import Messages from "./dbMessages.js";
//app config
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
//DB config
const connection_url =
"mongodb+srv://admin:0ZKon3XRmT0SWkal#cluster0.7pljv.mongodb.net/whatsappdb?retryWrites=true&w=majority";
mongoose.connect(connection_url, {
// useCreateIndex: true,
// useNewUrlParser: true,
// useUnifiedTopology: true,
});
//????
//api routes
app.get("/", (req, res) => res.status(200).send("hello world"));
app.post("/messages/new", (req, res) => {
const dbMessage = req.body;
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
//listen
app.listen(port, () => console.log(`Listening on localhost:${port}`));
dbmessages.js is given below
import mongoose from "mongoose";
const whatsappSchema = mongoose.Schema({
message: String,
name: String,
timestamp: String,
received: Boolean,
});
export default mongoose.model("messageContent", whatsappSchema);

You are not creating the instance of a model.
app.post("/messages/new", (req, res) => {
const dbMessage = req.body,
messageModel = new Messages();
message.Modelmessage = req.body.Modelmessage;
message.Modelname = req.body.Modelname;
messageModel.timestamp = req.body.timestamp;
messageModel.received = req.body.received;
messageModel.save().then(data => {
res.status(201).send(data);
}).catch((e) => {
res.status(500).send(err);
})
});

Related

0 I am working on NodeJs application it's shop application. I am trying to save posts in database and I am getting this error after submitting form:

TypeError: Post is not a constructor
owoce.js
const express = require('express');
const router = express.Router();
const Post = require('../models/owoc');
router.get('/', (req,res) => {
res.send('we are on owoce');
//try {
// const owoce = await Owoc.find()
// res.json(owoce)
// }catch (err){
// res.status(500).json({ message: err.message })
// }
})
// router.get('/jablka', (req,res) => {
// res.send('we are on jablka');
//});
router.post('/', (req,res) => {
const owoc = new Post({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
owoc.save()
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});
module.exports = router;
owoc.js it includes schema
const mongoose = require('mongoose');
const OwocSchema = new mongoose.Schema({
rodzaj: {
type: String,
required: true
},
kolor: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
//mongoose.Schema({
// username: String,
// password: String
//})
mongoose.exports = mongoose.model('Owoc', OwocSchema)
I am not sure what the problem is after looking at simmilar anwseres here
i dont see what should be changed
const Post = require('../models/owoc');
server.js adding it coz it may be usefull to troubleshoot
const express = require('express')
//const req = require('express/lib/request');
//const res = require('express/lib/response');
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
//const db = mongoose.connection('mongodb://localhost/sklep')
//MIDDLEWARES
app.use('/posts', ()=> {
console.log('This is a middleware');
});
//IMPORT ROUTES
const owoceRoute = require('./routes/owoce');
app.use('/owoce', owoceRoute);
//ROUTES
app.get('/', (req,res) => {
res.send('we are on home');
});
//connect to DB
mongoose.connect(
process.env.DB_CONNECTION ,mongoose.set('strictQuery', true), ()=> {
console.log('Connected to DB!!:))');
}); //{ useNewUrlParser: true})
//how to lisen to server
///db.on('error',(error) => console.error(error))
///db.once('open',() => console.log('connected to database'))
//db.on('connected', () => console.log('Connected to database'))
app.listen(3000, () => console.log('server started'))
I am adding screenshot and server code app despite not being sure if it will be any help
here is the screen from Postman
try this:
router.post('/create', async (req,res) => {
const owoc = await Owoc.create({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});

TypeError: Cannot read property 'username' of undefined in node.JS / express cannot post to route

I keep getting a type Error when posting to my exercises. here is my exercises route:
const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
Exercise.find()
.then(exercises => res.json(exercises))
.catch(err => res.status(400).json("error: " + err));
});
//add an exercise
router.route("/add").post((res, req) => {
//parse req.body
const username = req.body.username;
const description = req.body.description;
const duration = Number(req.body.duration);
const date = Date.parse(req.body.date);
//create new exercise object
const newExercise = new Exercise({
username,
description,
duration,
date
});
//save newExercise object
newExercise
.save()
.then(() => res.json("Exercise Added!"))
.catch(err => res.status(400).json("error: " + err));
});
module.exports = router;
and here is my model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
{
username: {
type: String,
required: true
},
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: Date,
required: true
}
},
{
timestamps: true
}
);
const Exercise = mongoose.model("Exercise", exerciseSchema);
module.exports = Exercise;
I've tried to change the route to router.post instead of router.route, I've tried changing the data model.
as well as my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();
//environment
const port = process.env.PORT || 5000;
//mongoose establish connection
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB connection established successfully");
});
//routers for users and exercises
const exercisesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");
app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);
//error log
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(`error: ${err}`).next();
});
app.listen(port, () => {
console.log(`server is up and running on port: ${port}`);
});
Here is the error logged in Insomnia:
Any Help is greatly appreciated!
You are misplace req and res in router.route("/add").post((res, req) => {.
Fix it: router.route("/add").post((req, res) => {

from nodejs app mongose.save() block and doesn't do anything?

I'm trying to use a very basic MongoDB method is to save a document on a database with mongoose.
1.I installed my MongoDB in centos 7
2.Create a database on the Mongo shell using: use mydatabase and insert a document inside it as normal.
3.Install mongoose and make a connection between my nodejs app and the MongoDB:
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
4. test the connection and all is fine with:
db.once('open', () => {
console.log('DB Connected');
});
Import the model schema as normal:
var { Classe } = require('../DBModels/GoClassDBModels/classes');
try to add new document like this:
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
newClasse.save()
My Model is:
const mongoose = require('mongoose');
const { Schema } = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model('Classes', classSchema);
module.exports = { Classe };
SERVER.JS:
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const cookieParser = require('cookie-parser');
const _ = require('lodash');
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log('server is started on 80');
});
mongoose.connect('mongodb://localhost:27017/goClass_test', {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once('open', () => {
console.log('DB Connected');
});
db.on('error', (err) => {
console.log(err);
});
var { Classe } = require('../DBModels/GoClassDBModels/classes');
const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(['lakkini.com']));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
'Cache-Control',
'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
);
next();
});
app.set('view engine', 'hbs');
app.use(express.static('/home/admin/SMS'));
app.use(express.static('/home/admin/assets'));
app.get('/', (req, res) => {
res.render('SMS/dashboard.hbs');
});
app.get('/classes', (req, res) => {
res.render('SMS/classes.hbs');
});
app.get('/inscription', (req, res) => {
res.render('SMS/inscriptions.hbs');
});
app.post('/saveClasse', (req, res) => {
var newClasse = new Classe({
label: 'hello',
level: 'level',
});
console.log('im gonna save the new class');
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log(response);
});
});
The problem is: nothing happened. No document has been inserted and no errors.
Can you suggest to me, please ?
PS: I'm trying to request from an HTTP server without HTTPS.
will that affect my requests nd block the save to the database?
result:
click to see the picture of the result please
Since the whole file was not given for mongoose connection and where save function is called , assuming you have structured it properly i'm giving my answer.
I was able to do this way,
The schema (same as yours) :
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;
var classSchema = new Schema({
directeurId: {
type: ObjectId,
},
label: {
type: String,
},
level: {
type: String,
},
studentNbr: {
type: String,
},
});
var Classe = mongoose.model("Classes", classSchema);
module.exports = { Classe };
Function to insert:
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("DB Connected");
var newClasse = new Classe({
label: "hello",
level: "level",
});
newClasse.save();
});
UPDATE:
SERVER.JS
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const cookieParser = require("cookie-parser");
const _ = require("lodash");
var app = express();
var server = http.createServer(app);
server.listen(80, () => {
console.log("server is started on 80");
});
mongoose.connect("mongodb://localhost:27017/goClass_test", {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(mongoose.connection.host);
console.log(mongoose.connection.port);
let db = mongoose.connection;
db.once("open", () => {
console.log("DB Connected");
});
db.on("error", (err) => {
console.log(err);
});
var { Classe } = require("./models/Classe");
// const goClasseRouteDirecteur = require('./GOClassRoutes/DirecteurRoutes/subRoutesClass');
app.use(bodyParser.json());
app.use(cookieParser(["lakkini.com"]));
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(function (req, res, next) {
res.set(
"Cache-Control",
"no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0"
);
next();
});
app.set("view engine", "hbs");
// app.use(express.static("/home/admin/SMS"));
// app.use(express.static("/home/admin/assets"));
// app.get('/', (req, res) => {
// res.render('SMS/dashboard.hbs');
// });
// app.get('/classes', (req, res) => {
// res.render('SMS/classes.hbs');
// });
// app.get('/inscription', (req, res) => {
// res.render('SMS/inscriptions.hbs');
// });
app.post("/saveClasse", (req, res) => {
var newClasse = new Classe({
label: "hello",
level: "level",
});
console.log("im gonna save the new class");
newClasse.save((err, response) => {
if (err) console.log(err);
else console.log("RESPONSE" + response);
});
});
I found the issue, but I don't understand why that.
the first structure was:
**
DBModel
classes.js
Server
server.js**
the structure right now:
**
DBModel
classes.js
server.js
**
I make out the server from that folder and all working fine...??
why that?

Heroku - Request timed out for fetching request

On localhost:5000/posts my data is successfully showing but if I do the same thing in Heroku: https://rest-in-peep.herokuapp.com/posts I get an application error. https://rest-in-peep.herokuapp.com/ works fine and I deployed it through Heroku GIT. I made sure to config my environmental vars in Heroku and added a Procfile but I am still getting this application error. I've been trying all day to figure this out but what I expect to happen is if I type in https://rest-in-peep.herokuapp.com/posts, I will get all the data that is being stored on my MongoDB database.
app.js file
const http = require("http");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv/config");
const app = express();
const server = http.createServer(app);
//Middlewares
app.use(cors());
app.use(bodyParser.json());
//Import Routes
const postsRoute = require("./routes/posts");
app.use("/posts", postsRoute);
//ROUTES
app.get("/", (req, res) => {
res.send("We are on home");
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("connected to MongoDB")
);
//How do we start listening to the server
server.listen(process.env.PORT || 5000, () => {
console.log("App now running on PORT");
});
routes>
posts.js
const express = require("express");
const Post = require("../models/Posts");
const router = express.Router();
//GETS BACK ALL THE POSTS
router.get("/", async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});
//SUBMITS A POST
router.post("/", async (req, res) => {
console.log(req);
const post = new Post({
quote: req.body.quote
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
//SPECIFIC POST
router.get("/:postId", async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});
//Delete Post
router.delete("/:postId", async (req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId });
res.json(removedPost);
} catch (err) {
res.json({ message: err });
}
});
//Update a post
router.patch("/:postId", async (req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{
$set: { quote: req.body.quote }
}
);
res.json(updatedPost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
gitignore
/node_modules
models>Posts.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
quote: {
type: String,
required: true
}
});
module.exports = mongoose.model("Posts", PostSchema);

MongoDB and Cosmos DB key error collection

I'm trying to create my first MongoDB app with Express & Angular & Azure Cosmos DB.
Here is my js files:
hero.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const heroSchema = new Schema({
id: {
type: Number,
required: true,
unique: true
},
name: String
}, {
collection: 'Heroes'
})
const Hero = mongoose.model('Hero', heroSchema);
module.exports = Hero;
mongo.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const env = require('./env/environment');
const mongoUri =
mongodb:`${env.accountName}:${env.key}#${env.accountName}
.documents.azure.com:10255/?ssl=true`
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri)
}
module.exports = {
connect,
mongoose
};
index.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes');
const root = './';
const port = process.env.PORT || '3000';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(root, 'docs')));
app.use('/api', routes);
app.get('*', (req, res) => {
res.sendFile('docs/index.html', {root});
});
route.js
const express = require('express');
const router = express.Router();
const heroService = require('./hero.service');
router.get('/heroes', (req, res) => {
heroService.getHeroes(req, res);
});
router.post('/hero', (req, res) => {
heroService.postHero(req, res);
});
router.put('/hero/:id', (req, res) => {
heroService.putHero(req, res);
});
router.delete('/hero/:id', (req, res) => {
heroService.deleteHero(req, res);
});
module.exports = router;
app.listen(port, () => console.log(`API running on
localhost:${port}`));
hero.service.js
const Hero = require('./hero.model');
require('./mongo').connect();
function getHeroes(req, res) {
const docquery = Hero.find({});
docquery
.exec()
.then(heroes => {
res.status(200).json(heroes);
})
.catch(error => {
res.status(500).send(error);
return;
});
}
function postHero(req, res) {
const originalHero = {
id: req.body.id,
name: req.body.name
};
const hero = new Hero(originalHero);
hero.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json(hero);
console.log('Hero created successfully!');
});
}
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
function putHero(req, res) {
const originalHero = {
id: parseInt(req.params.id, 10),
name: req.body.name
};
Hero.findOne({
id: originalHero.id
}, (error, hero) => {
if (checkServerError(res, error)) return;
if (!checkFound(res, hero)) return;
hero.name = originalHero.name;
hero.save(error => {
if (checkServerError(res, error)) return;
res.status(200).json(hero);
console.log('Hero updated successfully!');
});
});
}
function deleteHero(req, res) {
const id = parseInt(req.params.id, 10);
Hero.findOneAndRemove({
id: id
})
.then(hero => {
if (!checkFound(res, hero)) return;
res.status(200).json(hero);
console.log('Hero deleted successfully!');
})
.catch(error => {
if (checkServerError(res, error)) return;
});
}
function checkFound(res, hero) {
if (!hero) {
res.status(404).send('Hero not found.');
return;
}
return hero;
}
module.exports = {
getHeroes,
postHero,
putHero,
deleteHero
};
It only works when I POST a new hero for the first time and a second time gives me an error:
E11000 duplicate key error collection: admin.Heroes Failed _id or unique key constraint.
Please help!!
Thanks.
I know it's been a while but I've encountered the same problem. The solution is avoid using the field name id, rename it to UID or something. Once you done that you have to remove the entire collection and restart.
If you are following the Microsoft CosmosDB Angular tutorial, you can clone the repo below and test it on your local.
https://github.com/Azure-Samples/angular-cosmosdb
If you are using a newer version of mongoose you have to upgrade the connection string below.
//useMongoClient: true
useNewUrlParser: true

Resources