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);
Related
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.");
});
I have seen many issues before this in correlation to my issue but all the fixes haven't helped my issue. However, I can now pinpoint the issue. The issue only occurs when I try save a something to the MongoDB with my Message Schema, the connection to the DB is perfectly fine just anything in accordance to the Message Schema breaks it. This is shown as I also have a gridfs & multer setup to save images which works perfectly fine as you will see below and in the console log results. The code is not as clean as I want it to be as I have been trying to fix this for the past few hours.
server.js (entry point)
const express = require('express');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
const app = express();
const Grid = require('gridfs-stream');
const dbConnection = mongoose.createConnection('mongodb://localhost/messages', { useNewUrlParser: true, useUnifiedTopology: true });
let gfs;
dbConnection.once('open', () => {
console.log('Connected to MongoDB');
gfs = Grid(dbConnection.db, mongoose.mongo);
gfs.collection('uploads');
});
dbConnection.on('error', (err) => {
console.log('Error connecting to MongoDB: ' + err);
});
dbConnection.on('disconnected', () => {
console.log('Disconnected from MongoDB');
});
app.set('view engine', 'ejs');
const messageRouter = require('./routes/messages');
app.use('/posts', messageRouter);
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(methodOverride('_method'));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
models/message.js
const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
message: {
type: String,
required: true
},
author: {
type: String,
required: true
},
date: {
type: Date,
required: true,
default: Date.now()
},
attachment: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'File',
required: false
}
});
module.exports = mongoose.model('Message', messageSchema);
routes/messages.js
/*
Route for: host:port/posts
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const crypto = require('crypto');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const storage = new GridFsStorage({
url: 'mongodb://localhost/messages',
file: (req, file) => {
console.log('storage');
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
const Message = require('../models/message');
router.post('/', upload.single('attachment'), async (req, res) => {
console.log("post recieved");
console.log(req.body.author, req.body.message);
var message = new Message({
message: req.body.message,
author: req.body.author
});
try{
message = await message.save()
console.log("post made");
res.send('Message saved');
} catch (e) {
res.send(e);
console.error(e);
}
})
module.exports = router;
When I input all the info the image gets saved so it is clearly not a connection/auth based issue and the console logs
Server is running on port 3000
Connected to MongoDB
storage
post recieved
Name Message
MongooseError: Operation `messages.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Coding\[REDACTED]\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:151:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
The code had been working perfectly fine a month ago, I picked the project back up, edited a few lines and it has broken
I am creating my first node js api using Mongoose and Express. Facing some issue when i try to post the data it does not work. Postman request never completes and data does not get saved. Please find attached code and help me figure out the issue. Also note that db connection gets established successfully.
//Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
// Posts.js => Routes
const express = require("express");
const Post = require("../models/post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
// app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./routes/posts");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
UPDATE
Looks like something is wrong with db connection itself. Below is my connection string. I handled the mongoose connection on error and i get the error shown in screen shot.
mongodb://<dbuser>:<dbpassword>#ds023550.mlab.com:23550/roofapp
Just pasted your code here and is working fine for both post and get.
Are you able to complete the GET request?
How is your project structured?
Make sure you are importing the files correctly.
From your commented out file names you have Post.js with capital letter and you are importing posts. It seems that something is wrong in the imports.
Here is a working solution based on the code you've posted.
Files : app.js - Post.js - Router.js
app.js:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
// require("dotenv/config");
const bodyParser = require("body-parser");
//Import Routes
const postRoute = require("./Router");
//Middlewares
app.use(bodyParser.json());
//Routes
app.use("/posts", postRoute);
// Connect to db
mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to db !");
}
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: "string",
required: true,
},
description: {
type: "string",
required: true,
},
date: {
type: "Date",
default: Date.now,
},
});
module.exports = mongoose.model("Posts", PostSchema);
Router.js
const express = require("express");
const Post = require("./Post");
const router = express.Router();
router.get("/", (req, res) => {
res.send("Posts");
});
router.post("/", (req, res) => {
try {
console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
post
.save()
.then((data) => res.json(data))
.catch((err) => res.json(err));
} catch (error) {
console.log(error);
}
});
module.exports = router;
I am using Nodejs, MongoDB and Mongoose and while making a POST request I am getting error:
POST http://localhost:3000/subscribers
Content-Type: application/json
{
"name": "Lucky",
"subscribedToChannel": "Dev Tech"
}
Error: {
"message": "Subscriber validation failed: name: Path name is required., subscribedToChannel: Path subscribedToChannel is required."
}
The code snippet is mentioned below:
server.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
mongoose.connect(mongodb://localhost/subscribers, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const subscribersRouter = require('./routes/subscribers')
app.use('/subscribers', subscribersRouter)
app.listen(3000, () => console.log('Server Started'))```
---------------------------------------------------------------------------------------------------
routers/subscribers.js
const express = require('express')
const router = express.Router()
const Subscriber = require('../models/subscriber')
// Creating one
router.post('/', async (req, res) => {
const subscriber = new Subscriber({
name: req.body.name,
subscribedToChannel: req.body.subscribedToChannel
})
try {
const newSubscriber = await subscriber.save()
res.status(201).json(newSubscriber)
} catch (err) {
res.status(400).json({ message: err.message })
}
})
module.exports = router
----------------------------------------------------------------------------------------------------
models/subscriber.js
const mongoose = require('mongoose')
const subscriberSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
subscribedToChannel: {
type: String,
required: true
},
subscribeDate: {
type: Date,
required: true,
default: Date.now
}
})
module.exports = mongoose.model('Subscriber', subscriberSchema)
[1]: https://i.stack.imgur.com/rHf38.jpg
Use bodyParser above app.use(express.json())
Like : app.use(bodyparser.urlencoded({ extended : false }))
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};