Need help, I am trying to learn nodejs from youtube. I have created below but not getting any response from browser. Can you please check below code and advise what I have missed??
if I removed the courseModel.find ... from course.js and just write resp.send("XYZ") its showing on browser otherwise nothing is showing. please help
seems something is missing in mangodb connection string
--index.js
const connection = require('./model/connection');
const express = require('express');
const app = express();
const handleBars = require('express-handlebars');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const courseController = require('./controllers/course');
const server = http.createServer(app);
app.use(bodyParser.urlencoded({
extended: true,
}))
app.use("/course", courseController);
server.listen(3900, () => {
console.log("server is in running mode.");
});
--connection.js
const mongoose = require('mongoose');
var conn = mongoose.createConnection("mongodb://localhost:27017/learning", (err) => {
if (!err) {
console.log("Mongo db connected");
} else {
console.log(err);
}
});
const courseModels = require("./course.model");
--course.model.js
const mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
courseName: {
type: String,
required: 'Required'
},
courseId: {
type: String,
},
courseDuration: {
type: String,
}
});
module.exports = mongoose.model("Course", CourseSchema);
--course.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const courseModel = mongoose.model("Course");
router.get("/lists", (req, resp) => {
courseModel.find((err,docs)=>{
if(!err){
resp.send(docs)
}
});
});
module.exports = router;
--logs
issue resolved after updating the connection.js as below
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learning',
{
useNewUrlParser: true,
// useFindAndModify: false,
useUnifiedTopology: true
}, console.log("mongo db connected")
);
Insted of .
server.listen(3900, () => {
console.log("server is in running mode.");
});
use :
app.listen(3900, () => {
console.log("server is in running mode.");
});
Related
is anything I'm doing wrong, I get this error Error ValidationError: name: Path name is required., tech: Path tech is required. while POST the data in postman.
here is my index.js
const express = require('express')
const mongoose = require('mongoose')
const mongoDB = 'mongodb://127.0.0.1:27017/local_library'
const routers = require('../public/app')
const bodyParser = require("body-parser")
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/app', routers)
app.use(bodyParser.json());
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true })
const con = mongoose.connection
con.on('open', () => {
console.log('connected..')
})
app.use(express.json)
app.listen(3000, () => {
console.log('server started')
})
schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const SomeModelSchema = new Schema({
name: {
type: String,
required: true
},
tech: {
type: String,
required: true
},
})
module.exports = mongoose.model('SomeModel', SomeModelSchema )
app.js
const bodyParser = require('body-parser')
const express = require('express')
const router = express.Router()
const SomeModel = require('../models/schema.js')
router.get('/', async(req, res) => {
try{
const receive = await SomeModel.find()
res.json(receive)
}catch(err){
res.send('Error ' + err)
}
})
router.post ('/', async(req, res) => {
const send = new SomeModel({
name: req.body.name,
tech: req.body.tech,
})
try{
const a1 = await send.save()
res.json(a1)
}catch(err){
res.send('Error' + err)
}
})
module.exports = router
You need to select json option from postman body option.
choose type JSON in the your BODY
I am working with mongodb right now for creating an android app using react native.My problem is i am not able to post data to collection in mongodb.
My app.js code
const express = require("express");
const app = express();
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
app.use(cors());
app.options("*", cors());
//middleware
app.use(express.json());
app.use(morgan("tiny"));
//Routes
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const api = process.env.API_URL;
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/users`, usersRoutes);
app.use(`${api}/orders`, ordersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("Database Connection is ready...");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("server is running http://localhost:3000");
});
My categories.js:
const {Category} = require('../models/category');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) =>{
const categoryList = await Category.find();
if(!categoryList) {
res.status(500).json({success: false})
}
res.send(categoryList);
})
router.post('/', async (req,res)=>{
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color
})
category = await category.save();
if(!category)
return res.status(404).send('The category cannot be created!')
res.send(category);
})
module.exports = router;
My category.js:
const mongoose = require('mongoose');
const categorySchema = mongoose.Schema({
name: {
type: String,
required: true,
},
icon: {
type: String,
},
color: {
type: String,
}
})
exports.Category = mongoose.model('Category', categorySchema);
Through postman tool i checked it but there is no error even though i am unable to post the data and in mongodb database it is displaying as Query Results: 0
I'm new to MongoDB and I've been troubleshooting this issue for a while now and I simply can't figure it out. Every guide I follow results in a 404 and I'm not sure what I'm doing wrong.
Here's my file structure:
-models
image-upload.js
-routes
recogImages.js
server.js
image-upload.js
const mongoose = require("mongoose");
const imageUploadSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
uploadDate: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("ImageUpload", imageUploadSchema);
recogImages.js
const express = require("express");
const router = express.Router();
const ImageUpload = require("../models/image-upload");
//Getting all records
router.get("/", (req, res) => {
try {
const recogImages = ImageUpload.find();
res.json(recogImages);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
module.exports = router;
server.js
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const recogImageRouter = require("./routes/recogImages");
const app = express();
const port = 3000;
app.use(express.json());
mongoose.connect(process.env.DATABASE_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
// db.on("error", (error) => console.log(error));
db.on("error", console.error.bind(console, "MongoDB connection error"));
db.once("open", () => console.log("Connected to Database"));
app.use("./recog-images", recogImageRouter);
app.listen(port, () => console.log("server started on port: " + port));
Whether I run MongoDB locally or use Atlas, I get a connection to the database but when I query GET http://localhost:3000/recog-images/ I get 404 Not Found Cannot GET /recog-images/.
Try to change this line:
app.use("./recog-images", recogImageRouter);
to:
app.use("/vbox-recog", recogImageRouter);
I tried to make a MEAN stack app, but my API fails to give my requested data.
server.js file:
const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT;
const dburi = process.env.DB_URI;
//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');
mongoose.Promise = global.Promise;
mongoose.connect(
dburi,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
).then(
() => {
console.log('Connected to mongoDB');
},
(err) => console.log('Error connecting to mongoDB', err),
{ useNewUrlParser: true }
);
//Express app
const app = express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
console.log(`running at port ${port}`);
});
Routes file:
const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();
router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);
module.exports = router;
Controller file:
const VolcanoSchema = require('../models/volcano.models');
const getAllVulcanoes = (req, res) => {
VolcanoSchema.find((err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVolcanoes};
Model file
const mongoose = require('mongoose');
const VolcanoSchema = new mongoose.Schema({
Volcano_name:{
type: String,
},
Country:{
type: String,
},
Type:{
type: String,
},
Latitude:{
type: Number,
},
Longtitude:{
type: Number,
},
Elevation:{
type: Number,
},
});
module.exports = mongoose.model('Volcano', VolcanoSchema);
The thing is that i have a working example but most of the code is decrepitated... but it the respond is always giving me this
It would be nice if someone point out what i am doing wrong
EDIT: I switched to postgresql for my database hopefully this will work
You should fix the Controller (VulcanoSchema.find needs an empty object as parameter):
Controller file:
const VulcanoSchema = require('../models/vulcano.models');
const getAllVulcanoes = (req, res) => {
VulcanoSchema.find({}, (err, results) => {
if (err) {
console.log(err);
res.status(500).json({message: err});
} else {
res.status(200).json(results);
}
});
};
module.exports = {getAllVulcanoes};
I'm trying to create a simple REST api using Postman and the MERN stack
I have the following files
server.js, Item.js, items.js, keys.js
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const items = require('./routes/api/items');
const app = express();
// BodyParser Middleware
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
//Connect to Mongo
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
app.use('./api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started'));
Item.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
items.js
const express = require('express');
const router = express.Router();
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1 })
.then(items => res.json(items))
});
module.exports = router;
keys.js
module.exports = {
mongoURI: 'mongodb://tset:tset123#ds241012.mlab.com:41012/mern_shopping'
}
The server connects and connects to the DB - I get the console logs.
In postman if I try the GET and the url http://localhost:5000 I get
Cannot GET /
If I try http://localhost:5000/api/items I get
Cannot GET /api/items
Change this
app.use('./api/items', items);
to
app.use('/api/items', items);
and for http://localhost:5000 , the root you have to define with
app.get('/', function (req, res) {})